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

馋奶兔 提交于 2019-12-24 09:59:07

问题


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.


回答1:


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.




回答2:


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]




回答3:


#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]);




}


来源:https://stackoverflow.com/questions/8795969/dynamic-allocation-of-rows-of-2d-array-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!