在 C 中将多维数组作为函数参数传递
在 C
中,当我不知道多维数组的维数时,我是否可以将多维数组作为单个参数传递给函数?数组将是?
In C
can I pass a multidimensional array to a function as a single argument when I don't know what the dimensions of the array are going to be?
此外,我的多维数组可能包含字符串以外的类型.
Besides, my multidimensional array may contain types other than strings.
您可以使用任何数据类型执行此操作.只需将其设为指针:
You can do this with any data type. Simply make it a pointer-to-pointer:
typedef struct {
int myint;
char* mystring;
} data;
data** array;
但是不要忘记你仍然需要 malloc 变量,它确实变得有点复杂:
But don't forget you still have to malloc the variable, and it does get a bit complex:
//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() 的返回.)
The code to deallocate the structure looks similar - don't forget to call free() on everything you malloced! (Also, in robust applications you should check the return of malloc().)
现在假设你想把它传递给一个函数.您仍然可以使用双指针,因为您可能想要对数据结构进行操作,而不是指向数据结构指针的指针:
Now let's say you want to pass this to a function. You can still use the double pointer, because you probably want to do manipulations on the data structure, not the pointer to pointers of data structures:
int whatsMyInt(data** arrayPtr, int x, int y){
return arrayPtr[y][x].myint;
}
调用这个函数:
printf("My int is %d.
", whatsMyInt(array, 2, 4));
输出:
My int is 6.