extern 数组---不能通过sizeof计算数组大小
extern int a[]; //size of array
extern数组时,链接器并不知道数组的大小信息;
When compiling b.c, the compiler doesn't know the size of a
- you haven't told it. All it knows that an int array called a
exists in some other module. The linking process resolves object addresses, but not sizes.
如果extern声明数组的时候没有显示告诉链接器数组大小,链接器就不会知道数组大小,因此使用sizeof计算时编译器就会报错。
有以下两种方式extern,其中有一种会报错:
- extern声明时显示指定数组大小,则编译器不会报错
1 python@ubuntu:~/Documents/c_fundamental/extern_array$ cat provide_array.c 2 int iArray[] = {1,2,3,4,5}; 3 python@ubuntu:~/Documents/c_fundamental/extern_array$ cat call_array.c 4 #include<stdio.h> 5 6 extern int iArray[5]; 7 int main(void) 8 { 9 for(int i = 0; i < 5; i++) 10 { 11 printf("%d\n", iArray[i]); 12 } 13 printf("size of array: %zu", sizeof(iArray)); 14 15 return 0; 16 } 17 python@ubuntu:~/Documents/c_fundamental/extern_array$ gcc provide_array.c call_array.c -o extern_array 18 python@ubuntu:~/Documents/c_fundamental/extern_array$ ./extern_array 19 1 20 2 21 3 22 4 23 5 24 size of array: 20python@ubuntu:~/Documents/c_fundamental/extern_array$
- extern声明时未显示声明数组大小,则调用sizeof计算数组大小编译会报错
1 python@ubuntu:~/Documents/c_fundamental/extern_array$ cat call_array.c 2 #include<stdio.h> 3 4 extern int iArray[]; 5 int main(void) 6 { 7 for(int i = 0; i < 5; i++) 8 { 9 printf("%d\n", iArray[i]); 10 } 11 printf("size of array: %zu", sizeof(iArray)); 12 13 return 0; 14 } 15 python@ubuntu:~/Documents/c_fundamental/extern_array$ gcc provide_array.c call_array.c -o extern_array 16 call_array.c: In function ‘main’: 17 call_array.c:10:37: error: invalid application of ‘sizeof’ to incomplete type ‘int[]’ 18 printf("size of array: %zu", sizeof(iArray)); 19 ^ 20 python@ubuntu:~/Documents/c_fundamental/extern_array$