The function is declared to take a jagged array, i.e. an array that could have different sizes in each of its rows.
void f (int** arr,int n)
Such an array needs to be created differently - you need to allocate n
pointers, and then allocate an individual memory block for each of the array rows:
int **arr = malloc(sizeof(int*)*n);
for (int i = 0; i != n ; i++) {
// This code uses the same size for each row, but jagged arrays
// are free of the "rectangular array" limitations.
arr[i] = malloc(sizeof(int)*n);
}
Once you use such an array, free its rows before freeing the array itself:
for (int i = 0; i != n ; i++) {
free(arr[i]);
}
free(arr);
Can you explain why what i am doing is not correct?
The reason why what you are doing is incorrect is that you are presenting a rectangular array to a function that expects a jagged array. The two have very different memory structures.
Rectangular array that you initialize statically is a single, contiguous, block of memory of size 25*sizeof(int)
. The "second dimension" is added to that flat chunk of memory by compiler's knowledge that the second dimension has exactly five elements. That's how the compiler can apply a "cookie cutter" to the block, partitioning it in five equal blocks of five integers. Accessing an element at (i,j)
is translated to adding 5*i+j
offset to the base address of arr
(a single pointer dereference).
Jagged array, on the other hand, is an array of pointers to arrays. It has a size of 5*sizeof(int*)
. Each of these pointers can point to a separate array. Accessing an element at (i,j)
is translated to accessing arr[i]
pointer, and then accessing the value at the offset taken from that value (two pointer dereferences).