Wednesday, October 21, 2009

Passing multi-dimensional arrays to functions in C

Here is how to initialize and pass multi-dimensional arrays to functions in ANSI C :

void printArray(int **array, int m, int n)
{
    int i, j;
    for(i = 0; i < m; i++) {
        for(j = 0; j < n; j++) {
            printf("%d\n", array[i][j]);
        }
    }
}

int main()
{
      int i, j, k = 0, m = 5, n = 20;
      int **a = malloc(m * sizeof(*a));
   
      //Initialize the arrays
      for (i = 0; i < m; i++) { 
          a[i]=malloc(n * sizeof(*(a[i])));
      }
      for (i = 0; i < m; i++) {
          for (j = 0; j<n; j++) {
              k++; 
              a[i][j] = k;
          }
      }
   
      printArray(a, m, n);
      
      //Free allocated memory of the array
      for (i = 0; i < m; ++i) {
        free(a[i]);
      }
      free(a);
   
      return 0;
}

2 comments:

Reuben Sammut said...

i know it's just test code but don't forget to free allocated memory

Dreas said...

Yes, you're right Reuben; thanks for the mention.

Updated code sample to free the memory used by the array.

Post a Comment