In c++, I can create a 2D array with fixed number of columns, say 5, as follows:
char (*c)[5];
then I can allocate memory for rows as follows
c = new char[n][5];
where n can be any variable which can be assigned value even at run time. I would like to know whether and how can I dynamically allocate variable amount of memory to each row with this method. i.e. I want to use first statement as such but can modify the second statement.
Instead of a pointer to an array, you'd make a pointer to a pointer, to be filled with an array of pointers, each element of which is in turn to be filled with an array of chars:
A somewhat more C++ data structure would be a
std::vector<std::string>
.As you noticed in the comment, dynamic arrays allocated with
new[]
cannot be resized, since there is no analogue ofrealloc
in C++ (it doesn't make sense with the object model, if you think about it). Therefore, you should always prefer a proper container over any manual attempt at dynamic lifetime management.In summary: Don't use
new
. Ever. Use appropriate dynamic containers.You need to declare c as follows:
char** c
; then, allocate the major array as follows:c = new char*[n]
; and then, allocate each minor array as follows:c[i] = new char[m]