gpt4 book ai didi

c++ - 二维数组初始化

转载 作者:行者123 更新时间:2023-11-28 00:54:16 24 4
gpt4 key购买 nike

案例 1:

int nrows=5;
int ncols=10;
int **rowptr;
rowptr=new int*;
for(int rows=0;rows<nrows;rows++) {
for(int cols=0;cols<ncols;cols++) {
*rowptr=new int;
}
}

案例 2:

int nrows=5;
int ncols=10;
int **rowptr;
for(int rows=0;rows<nrows;rows++) {
rowptr=new int*;
for(int cols=0;cols<ncols;cols++) {
*rowptr=new int;
}
}

我可以使用这两种方式插入和打印值。初始化有什么区别?

最佳答案

What is the difference?

#1 只是分配足够的内存来容纳一个整数指针,而不是一个整数指针数组。
#2 仅通过覆盖前一次迭代的内存分配导致内存泄漏。

I am able to insert and print values using both the ways

内存泄漏和未定义行为可能不会在您的程序中立即产生可观察到的错误结果,但它们肯定是 Murphy's Law 的好例子

正确的做法是:

int nrows = 5;
int ncols = 10;

//Allocate enough memory for an array of integer pointers
int **rowptr = new int*[nrows];

//loop through the array and create the second dimension
for (int i = 0;i < nrows;i++)
rowptr[i] = new int[ncols];

关于c++ - 二维数组初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12423395/

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