[英]Passing dynamically allocated 2d array to a function
The following code is not working correctly. 以下代码无法正常工作。 I'm getting a segfault when I run the program.
我运行程序时遇到了段错误。 I ran my program through gdb and found out that the error is occuring in the fillArrays(int**,int) function.
我通过gdb运行我的程序,发现fillArrays(int **,int)函数中发生了错误。
GDB is displaying the following parameters for fillArrays(int**,int): GDB正在为fillArrays(int **,int)显示以下参数:
fillArrays (arrays=0x0,numArrays=3)
Here is the source code to my program 这是我的程序的源代码
#include <stdlib.h> /* malloc and free */
#define MULTIPLIER 1
#define SMALL 10
#define BIG 20
void allocateSmallArrays(int **arrays,int numArrays) {
int index,freeIndex;
int outerIndex,innerIndex;
arrays = malloc(numArrays*sizeof(int*));
if(arrays == NULL) {
printf("out of memory\n");
exit(1);
}
for(index = 0;index < numArrays;index++) {
arrays[index] = malloc(SMALL*sizeof(int));
if(arrays[index] == NULL) {
printf("out of memory\n");
exit(1);
}
}
}
void fillArrays(int **arrays,int numArrays) {
int outerIndex,innerIndex;
for(outerIndex = 0;outerIndex < numArrays;outerIndex++) {
for(innerIndex = 0;innerIndex < SMALL;innerIndex++)
arrays[outerIndex][innerIndex] = 0;
}
}
void deallocateSmallArrays(int **arrays,int numArrays) {
int index;
for(index = 0;index < numArrays;index++)
free(arrays[index]);
free(arrays);
}
int main(void) {
int numArrays = (3 * MULTIPLIER);
int **arrays = 0;
allocateSmallArrays(arrays,numArrays);
fillArrays(arrays,numArrays);
deallocateSmallArrays(arrays,numArrays);
arrays = 0;
return 0;
}
I was under the assumption that since arrays was allocated in allocateSmallArrays, that passing it through fillArrays would 0 out the allocated arrays and then deallocate in the last function. 我假设因为数组是在allocateSmallArrays中分配的,所以将它传递给fillArrays会使分配的数组失效,然后在最后一个函数中释放。 How do I go about accomplishing this?
我该如何完成这项工作?
The problem is that allocateSmallArrays
changes its own copy of the arrays
pointer . 问题是
allocateSmallArrays
更改了自己的arrays
指针副本 。 So the result of the malloc
is lost and after the function is done, in the caller arrays
is still 0. You could: 所以
malloc
的结果丢失了,在函数完成后,调用者arrays
仍为0.你可以:
Pass a triple pointer int ***arrays
and do to *arrays
everything you're doing to arrays
传递一个三重指针
int ***arrays
并对你对*arrays
所做的一切进行*arrays
arrays
Return the pointer instead of void 返回指针而不是void
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.