gpt4 book ai didi

c++ - 动态二维数组 : int (*ptr)[4] = new int[7][4];

转载 作者:太空狗 更新时间:2023-10-29 20:37:49 25 4
gpt4 key购买 nike

据我所知,动态分配的二维数组应该这样分配:

int **rows = new int*[7]; 
//for loop assigning all seven rows[i] a "new int[4]"

但是,以下也适用于我:

int (*ptr)[4] = new int[7][4];  //create dynamic 2d array
for(int i = 0; i < 7; ++i) //initialize and test
{
for(int j = 0; j < 4; ++j)
{
ptr[i][j] = i + j;
cout << ptr[i][j] << ' ';
}
cout << endl;
}
delete[] ptr;

/*
output:
0 1 2 3
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
5 6 7 8
6 7 8 9
*/

为什么我应该使用我首先提到的更复杂的方法,当我可以用这一行创建动态二维数组时:

int (*ptr)[4] = new int[7][4];

我很感激任何见解!

(我没有发现使用 valgrind 的内存泄漏。)

最佳答案

Why should I use the more complicated method I mentioned first, when I can create a dynamical 2d array with this one line:

当行中的列数不同时,您将需要它。假设您有一个二维数组,如下所示:

1 2 3 4 5 6 7 8 9 10
1 2 3 4
9 8 8 5 6 4

对于这种情况,第二种方法将行不通。您需要使用:

p[0] = new int[10];
p[1] = new int[4];
p[2] = new int[6];

关于c++ - 动态二维数组 : int (*ptr)[4] = new int[7][4];,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33658890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com