您可以使用任何数据类型。只需使其成为指针指针:
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
//malloc the 'x' dimension
array[y] = malloc(sizeof(data) * w);
//iterate over the 'x' dimension
for(x=0;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()对你的错误! (此外,在健壮的应用程序,你应该check the return of 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.