| | |
allocating a 2D array
Please support our C++ advertiser: Intel Parallel Studio Home
![]() |
It's not a problem to allocate 2D array or what else in C++. The problem is: how do you want access the allocated storage. You know that it's impossible to declare 2D array variable with run-time defined extents in C and C++.
The most straightforward approach in C style but with templates (w/o argument check):
More elaborated approaches: define your own class encapsulated all mechanics described above, use vector<vector< >> or valarray<valarray< >> templates. Search this forum: it was a very popular theme 1 or 2 month ago.
Search inet: there are lots of Matrix classes which implements 2D dynamic arrays logics.
The most straightforward approach in C style but with templates (w/o argument check):
C++ Syntax (Toggle Plain Text)
template <typename T> T** new2D(size_t m, size_t n) { T** pp = new T*[m]; T* p = new T[m*n]; for (size_t i = 0; i < m; ++i, p += n) pp[i] = p; return pp; } ... double** pa2d = new2D<double>(m,n); ... pa2d[i][j]... // to deallocate: delete pa2d[0]; delete pa2d;
Search inet: there are lots of Matrix classes which implements 2D dynamic arrays logics.
Last edited by ArkM; Nov 8th, 2008 at 3:44 pm.
![]() |
Similar Threads
- Safe Array (C++)
- Resizing of an array. (C++)
- finding the point where a loop begins (C)
- Large array allocation in VB (Visual Basic 4 / 5 / 6)
- Sane way of dynamically allocating arrays beyond declaration. (C)
- Run-time Error when printing Array Contents. (C)
- Array declaration problem (C++)
Other Threads in the C++ Forum
- Previous Thread: Hangman help
- Next Thread: What is the cleanest way to share variables and functions between classes???
| Thread Tools | Search this Thread |
api array beginner binary bitmap c++ c/c++ calculator char char* class classes coding compile compiler console conversion count data database delete desktop developer directshow dll download dynamic email encryption error file forms fstream function functions game getline google graph gui homeworkhelper iamthwee ifstream input int integer java lib linkedlist linker linux loop looping loops map math matrix memory multiple news node number numbertoword output parameter pointer problem program programming project proxy python random read recursion recursive reference return rpg sorting string strings struct template templates test text text-file tree unix url vector video visualstudio win32 windows winsock word wordfrequency wxwidgets






