在C中将多维数组作为函数参数传递
时间:2020-03-05 18:38:10 来源:igfitidea点击:
当我不知道数组的尺寸是多少时,可以在C语言中将多维数组作为单个参数传递给函数吗?
另外,我的多维数组可能包含字符串以外的类型。
解决方案
回答
我们可以使用任何数据类型来执行此操作。只需使其成为指针到指针即可:
typedef struct { int myint; char* mystring; } data; data** array;
但是请不要忘记,我们仍然必须malloc该变量,它确实变得有点复杂:
//initialize int x,y,w,h; w = 10; //width of array h = 20; //height of array //malloc the 'y' dimension array = malloc(sizeof(data*) * h); //iterate over 'y' dimension for(y=0;y<h;y++){ //malloc the 'x' dimension array[y] = malloc(sizeof(data) * w); //iterate over the 'x' dimension for(x=0;x<w;x++){ //malloc the string in the data structure array[y][x].mystring = malloc(50); //50 chars //initialize array[y][x].myint = 6; strcpy(array[y][x].mystring, "w00t"); } }
用于解除分配结构的代码看起来类似,不要忘记对已分配的所有内容调用free()! (此外,在健壮的应用程序中,我们应该检查malloc()的返回。)
现在,假设我们要将其传递给函数。我们仍然可以使用双指针,因为我们可能想对数据结构进行操作,而不是对数据结构的指针进行操作:
int whatsMyInt(data** arrayPtr, int x, int y){ return arrayPtr[y][x].myint; }
使用以下命令调用此函数:
printf("My int is %d.\n", whatsMyInt(array, 2, 4));
输出:
My int is 6.
回答
将显式指针传递给第一个元素,并以数组维度作为单独的参数。例如,要处理任意大小的int二维数组:
void func_2d(int *p, size_t M, size_t N) { size_t i, j; ... p[i*N+j] = ...; }
这将被称为
... int arr1[10][20]; int arr2[5][80]; ... func_2d(&arr1[0][0], 10, 20); func_2d(&arr2[0][0], 5, 80);
相同的原则适用于高维数组:
func_3d(int *p, size_t X, size_t Y, size_t Z) { size_t i, j, k; ... p[i*Y*Z+j*Z+k] = ...; ... } ... arr2[10][20][30]; ... func_3d(&arr[0][0][0], 10, 20, 30);