【发布时间】:2011-05-18 13:13:31
【问题描述】:
我正在尝试使用以下函数代码创建一个多维 int 数组:
int ** createIntMatrix(unsigned int rows, unsigned int cols)
{
int ** matrix;
unsigned int i,j;
matrix = (int **) calloc(cols, sizeof(int *));
for(i = 0; i < cols; i++)
matrix[i] = (int *) calloc(rows, sizeof(int));
for(i = 0; i < cols; i++)
for(j = 0; j < rows; j++)
matrix[i][j] = 0;
return matrix;
}
我在下面的代码中使用这个函数创建了三个实例,
cout<<"allocating temporary data holders..."<<endl;
int ** temp_meanR;
int ** temp_meanG;
int ** temp_meanB;
temp_meanR = createIntMatrix(img->height,img->width);
temp_meanG = createIntMatrix(img->height,img->width);
temp_meanB = createIntMatrix(img->height,img->width);
cout<<"....done!"<<endl;
我正在访问这些元素,例如 temp_meanB[4][5]。
但不幸的是,我在运行时收到以下错误:
allocating temporary data holders...
....done!
tp6(1868) malloc: *** error for object 0x122852e08: incorrect checksum for freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug
Abort trap
我哪里错了?
【问题讨论】:
-
你为什么用 calloc 而不是 new?
-
如果您使用
calloc分配内存,则无需手动将元素初始化为零。根据cplusplus.com/reference/clibrary/cstdlib/calloc,所有位都自动设置为0。 -
malloc 是 C 方式,在 C++ 中使用 new。
标签: c++ multidimensional-array malloc