# 在C中传递多维数组作为函数参数

0

## 4 答案

``````typedef struct {
int myint;
char* mystring;
} data;

data** array;
``````

``````//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``````

``````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.
``````
0

``````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);
``````
0

``````f(int size, int data[][size]) {...}
``````

GNU C允许参数声明转发（如果您确实需要在数组之后传递维度）：

``````f(int size; int data[][size], int size) {...}
``````

0

``````int matmax(int **p, int dim) // p- matrix , dim- dimension of the matrix
{
return p[0][0];
}

int main()
{
int *u[5]; // will be a 5x5 matrix

for(int i = 0; i < 5; i++)
u[i] = new int[5];

u[0][0] = 1; // initialize u[0][0] - not mandatory

// put data in u[][]

printf("%d", matmax(u, 0)); //call to function
getche(); // just to see the result
}
``````
0