zoukankan      html  css  js  c++  java
  • 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,其中有一种会报错:

    1. 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
      ", 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$
    2. 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
      ", 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$
  • 相关阅读:
    提高CRM系统实施成功率
    CRM销售管理软件实施的误区
    ERP、CRM、SCM之间的区别
    选择CRM系统的四个步骤
    [导入]163相册验证码图片的识别手记之一 去除干扰
    [导入]C#中WebService里的回车符"\r"丢失问题
    [导入]文件同步精灵(初版)
    [导入]163相册验证码图片的识别手记之二 识别
    [导入]电信对我们的侵权行为如何能得到法律保护?
    [导入]认父亲的DbParameter!!
  • 原文地址:https://www.cnblogs.com/taouu/p/14672657.html
Copyright © 2011-2022 走看看