dynamic allocation of rows of 2D array in c++

2019-08-14 05:00发布

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.

3条回答
太酷不给撩
2楼-- · 2019-08-14 05:17

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:

char ** c = new char*[n];  // array of pointers, c points to first element

for (unsigned int i = 0; i != n; ++i)
    c[i] = new char[get_size_of_array(i)]; // array of chars, c[i] points to 1st element

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 of realloc 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.

查看更多
萌系小妹纸
3楼-- · 2019-08-14 05:31
#include <iostream>
using namespace std;

main()
{
    int row,col,i,j;
    cout<<"Enter row and col\n";
    cin>>row>>col;

    int *a,(*p)[col]=new (int[row][col]);
    for(i=0;i<row;i++)
            for(j=0;j<col;j++)
                p[i][j]=i+j;

        for(i=0;i<row;i++)
            for(j=0;j<col;j++)
                cout<<i<<" "<<j<<" "<<p[i][j]<<endl;
                //printf("%d %d %d\n",i,j,p[i][j]);




}
查看更多
三岁会撩人
4楼-- · 2019-08-14 05:33

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]

查看更多
登录 后发表回答