Why is it necessary to pass the number of columns as a function argument?
When I pass the matrix in the parameters to a function using parentheses, I need to pass the column numbers as well. Why?
#include <stdio.h>
//int function(int matrix[][5]){ //Will work
int function(int matrix[][]){ //Won't work
return matrix[0][0];
}
int main(){
int matrix[5][5];
matrix[0][0] = 42;
printf("%d", function(matrix));
}
Gcc error:
prog.c:3:18: error: array type has incomplete element type
int function(int matrix[][]){
^
prog.c: In function ‘main’:
prog.c:10:5: error: type of formal parameter 1 is incomplete
printf("%d", function(matrix));
^
prog.c:7: confused by earlier errors, bailing out
thank
source to share
In memory int
will be placed contiguously. Unless you provide everything but the first dimension, there is no way to determine the location of the int object you are requesting. if your matrix
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
It still appears in memory as:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
if I know that the second dimension has 5 in it int
then matrix[2][1]
is at the address matrix + (2 * 5) + 1
, I have to go through 5 columns, twice to go to the third row, then another element to that row to get the column. Without the size of the second dimension, I cannot figure out where the values will map to in memory. (in this case "I" stands for compiler / runtime)
source to share