Function declaration void setArr(int x[2][2], int a, int b)
declares setArr
as a function that takes as a first parameter an array of 2 arrays each holding 2 integers. Whereas in the main
you declare arr
(the variable you pass to setArr
) as int *arr[2]
, that is as a pointer to an array of 2 integers.
The solution is to either change your code in main
, for example by declaring arr
as int arr[2][2]
and remove the for loop, or change the setArr
so that it takes a pointer to an array of two integers void setArr(int *x[2], int a, int b)
.
I'm not sure if the latter could cause any problems (gcc -Wall
compiles without warnings), but one thing to notice is the difference in memory layout when declaring arr
as a pointer to an array of size 2 or declaring it as an array of 2 arrays of size 2. Compiling and executing the following should show you the difference:
int main(void) {
int *arr[2];
for (int i = 0; i < 2; i++) {
arr[i] = malloc(sizeof(int) * 2);
}
printf("The address of arr[0] is %p\n", &arr[0]);
printf("The address of arr[1] is %p\n\n", &arr[1]);
printf("The address of arr[0][0] is %p\n", &arr[0][0]);
printf("The address of arr[0][1] is %p\n", &arr[0][1]);
printf("The address of arr[1][0] is %p\n", &arr[1][0]);
printf("The address of arr[1][1] is %p\n\n", &arr[1][1]);
int arr2[2][2];
printf("The address of arr2[0] is %p\n", &arr2[0]);
printf("The address of arr2[1] is %p\n\n", &arr2[1]);
printf("The address of arr2[0][0] is %p\n", &arr2[0][0]);
printf("The address of arr2[0][1] is %p\n", &arr2[0][1]);
printf("The address of arr2[1][0] is %p\n", &arr2[1][0]);
printf("The address of arr2[1][1] is %p\n", &arr2[1][1]);
// setArr(arr, 2, 2);
}
Running the executable once on my machine I got the following:
The address of arr[0] is 0x7ffe43d226b0
The address of arr[1] is 0x7ffe43d226b8
The address of arr[0][0] is 0xb62010
The address of arr[0][1] is 0xb62014
The address of arr[1][0] is 0xb62030
The address of arr[1][1] is 0xb62034
The address of arr2[0] is 0x7ffe43d226c0
The address of arr2[1] is 0x7ffe43d226c8
The address of arr2[0][0] is 0x7ffe43d226c0
The address of arr2[0][1] is 0x7ffe43d226c4
The address of arr2[1][0] is 0x7ffe43d226c8
The address of arr2[1][1] is 0x7ffe43d226cc
You can see that the when declaring arr
as an pointer to an array, the two arrays of two integers are not contiguous, whereas when declaring it as an array of arrays, they are. Moreover, when declaring it as an array of arrays there is no need to dynamically allocate memory (e.g., using malloc
).