Wet Feet Wet Feet - 3 months ago 19
C Question

Passing multidimensional arrays as arguments in functions in C

I am currently doing the fifteen exercise in CS50's Problem set 3. However, I am stuck in figuring out the syntax to pass a multi-dimensional array as an argument to a function. For instance, the following code (which prints out some numbers in an array) compiles and works:

#include <stdio.h>

void func(int array[], int size);

int main()
{
int size = 3;
int array[3] = {1,2,3};
func(array,size);
printf("Done\n");
}

void func(int array[], int size)
{
printf("%i %i %i\n", array[0],array[1], array[2]);
}


But this doesn't:

#include <stdio.h>

void func(int array[], int size);

int main()
{
int size = 3;
int array[2][2] = {{1,2,3},{4,5,6},{7,8,9}};
func(array,size);
printf("Done");
}

void func(int array[], int size)
{
printf("%i %i %i\n", array[0][0],array[1][1], array[2][2]);
}


This is the error provided by clang:

test.c:3:20: error: array has incomplete element type 'int []'
void func(int array[][], int size);
^
test.c:13:20: error: array has incomplete element type 'int []'
void func(int array[][], int size)


Can anyone explain to me what's wrong with my syntax? I don't quite understand the error messages given to me by clang.

Answer

The function func() expects a pointer to int but you are passing a pointer to an array. Hence, the errrors. It's because an array gets converted into a pointer to its first element when you pass it to a function.

You can change the function prototype and definition to receive a pointer to an array:

void func(int (*array)[3], int size);

int main()
{
    int size = 3;
    int array[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
    func(array,size);
    printf("Done");
}

void func(int (*array)[3], int size) {
  ...
}

Note that your array is initialized with size 3x3. So the array size has to 3x3 at least.


C99 allows to you pass dimensions. So you can write it like this too:

void func(int x, int y, int a[x][y]);

int main()
{
    int size = 3;
    int array[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
    func(3, 3, array);
    printf("Done");
}

void func(int x, int y, int array[x][y])
{
    printf("%i %i %i\n", array[0][0],array[1][1], array[2][2]);
}
Comments