初始化在C零的双指针++ [英] Initialize a double pointer with zeros in C++
问题描述
我有一个二维数组。不过我使用指针的指针,而不是常规的数组。我希望能够给所有的值为零复位,而无需使用过的行和列的循环。可能吗?如果是的话,怎么样?用memset(数组,0,sizeof的(阵列))似乎不应该做的工作。例如:code:
双**阵列=新的双* [SIZE]
为(unsigned int类型I = 0; I<大小;我++)
数组[我] =新的双[SIZE]
memset的(数组,0,sizeof的(阵列));
你有什么是一个指向指针的动态分配的数组。其中每个点双打的动态分配的数组。 否,你不能没有迭代访问这些双打和取消引用指针。
您例如code确实这是什么设置 cell_pair_matrix [0]
(或者它应该是数组[0]
?),从而空泄漏双打的分配的数组。
当你在第一个地方分配你可以初始化值为零:
cell_pair_matrix [I] =新的双[SIZE](); //注意最后括号
甚至更好,使用的std ::矢量
,让标准库管理内存。
I have a 2D array. However I am using pointer to pointer instead of the regular array. I want to be able to reset all the values to zero without using a loop over rows and columns. Is it possible? If yes, how? Using memset(array, 0, sizeof(array)) doesn't seem to do the right job. Example code:
double** array = new double*[SIZE];
for (unsigned int i = 0; i < SIZE; i++)
array[i] = new double[SIZE];
memset(array, 0, sizeof(array));
What you have is a pointer to a dynamically allocated array of pointers. Each of those point to a dynamically allocated array of doubles. No, you cannot access those doubles without iterating and dereferencing the pointers.
What your example code does is it sets the cell_pair_matrix[0]
(or should it be array[0]
?) to null thereby leaking the allocated array of doubles.
You could initialize the values to zero when you allocate in the first place:
cell_pair_matrix[i] = new double[SIZE](); // note the brackets at the end
Or even better, use std::vector
and let the standard library manage the memory.
这篇关于初始化在C零的双指针++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!