简体   繁体   中英

Why is it necessary pass the number of columns as a function argument?

When I pass a matrix in the parameters of the function, using brackets, I need pass the numbers of columns too. 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

Thanks

In memory, the int s will be laid out contiguously. If you don't provide all but the first dimension, there's no way to figure out the location of the int you are requesting. if your matrix is

 1  2  3  4  5
 6  7  8  9 10
11 12 13 14 15

In memory it still appears as:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

if I know the second dimension has 5 int s in it, then matrix[2][1] is at address matrix + (2 * 5) + 1 , I must go in by 5 columns, two times, to get to the third row, then one more element into that row to get the column. Without the size of the second dimension, I have no way of figuring out where the values will appear in memory. (in this case "I" means the compiler/runtime)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM