Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing multidimensional arrays as function arguments in 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.

like image 248
David Avatar asked Aug 06 '08 22:08

David


People also ask

Can you pass multidimensional array to a function?

To pass multidimensional arrays to a function, only the name of the array is passed to the function (similar to one-dimensional arrays).

Can one-dimensional array be passed as function arguments in C language?

Both one-dimensional arrays and multidimensional arrays can be passed as function arguments.

How do you pass a 2D array to a function pointer?

for (int row = 0; row<SIZE; row++) { for (int col = 0; col<SIZE; col++) { array[row][col] = 'a'; // or whatever value you want } } // Print it printarray(array, SIZE); ... Show activity on this post. Show activity on this post. You can easily pass the 2d array using double pointer.

How do you pass a 3d array to a function?

1 #include <stdio. h> 2 #include <stdlib. h> 3 4 void print_2d_array_of_pointers(int rows, int cols, int **a) { 5 for(int i = 0; i < rows; ++i) { 6 for(int j = 0; j < cols; ++j) { 7 printf("%d ", a[i][j]); 8 } 9 printf("\n"); 10 } 11 } 12 13 // ...


1 Answers

Pass an explicit pointer to the first element with the array dimensions as separate parameters. For example, to handle arbitrarily sized 2-d arrays of int:

void func_2d(int *p, size_t M, size_t N) {   size_t i, j;   ...   p[i*N+j] = ...; } 

which would be called as

... int arr1[10][20]; int arr2[5][80]; ... func_2d(&arr1[0][0], 10, 20); func_2d(&arr2[0][0], 5, 80); 

Same principle applies for higher-dimension arrays:

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); 
like image 140
John Bode Avatar answered Sep 21 '22 10:09

John Bode