C++实操 - 如何判断外部引用数组的大小 & 如何外部引用常量

在C语言中,在一个文件中定义的数组,在另一个文件中使用时,sizeof操作符是不能使用的。

file1.c:                 

int array[ ] = {1, 2, 3};        

file2.c:

extern int array[ ];

一个未指定大小的外部数组是一个不完整的类型;你不能对它应用sizeof。sizeof在编译时操作,没有办法了解一个在其他文件中定义的数组的大小。

你有三个选择:

第一种:

在定义数组的同一个源文件中声明一个包含数组大小的配套变量,并对其进行定义和初始化(用sizeof)。

file1.c:

int array[] = {1, 2, 3};

int arraysz = sizeof(array);

file2.c:

extern int array[ ];

extern int arraysz;

第二种:

为大小定义一个常量,这样它就可以在定义和extern声明中统一使用。

file1.h。

#define ARRAYSZ 3

extern int array[ARRAYSZ]。

file1.c:

#include "file1.h"        

int array[ARRAYSZ]。

file2.c:

#include "file1.h"

第三种:

在数组的最后一个元素中使用一些哨兵值(通常是0,-1,或NULL),这样代码就可以在没有明确的大小指示的情况下确定结束。

file1.c:

int array[] = {1, 2, 3, -1};

file2.c:

extern int array[ ];

(显然,选择在一定程度上取决于数组是否已经被初始化;如果已经被初始化,那么第二种方法就不如第三种方法好)。

第四种:

其实这最后一种才是最方便的,在GCC的C编译器和C++编译器上都试过,都是可行的。

就是在extern的时候,指定数组的大小。要保证extern声明的数组大小和定义大小要一致,否则会提示error。

file1.c

int array[100];

file2.c

extern int array[100];

int main( )

{

  int len = sizeof(array);

  return 0;

}

------------------------------------- 

上面说的第一种方法里,可以将数组的长度定义为常数,这个长度编译时就确定并且后面不会更改。

file1.c:

int array[] = {1, 2, 3};

const int arraysz = sizeof(array)/sizeof(array[0]);


file2.c:

#include <stdio.h>

extern int array[ ];


/* extern int也可以;extern int const也可以。*/

extern const int arraysz; 


int main()
{
  printf("%d\n", array[arraysz-1]);

  return 0;
}


$ gcc -o test file1.c file2.c

如果使用C++的话,就要注意在定义常量时也要加上extern,因为C++的const变量默认是static的。

file1.cpp:

int array[] = {1, 2, 3};

extern const int arraysz = sizeof(array)/sizeof(array[0]);



file2.cpp:

#include <stdio.h>
extern int array[ ];



/* extern int也可以;extern int const也可以。*/

extern const int arraysz;



int main()
{
  printf("%d\n", array[arraysz-1]);
  return 0;
}


$ g++ -o test file1.cpp file2.cpp

在C++中,在定义常量的源文件中,要在定义时加上extern修饰符,或者多加一个extern的声明也可以。

// 1, 定义并初始化时加extern

extern const int length = 10;

// 2, 初始化时不加extern,单独用extern声明

extern const int length;

const int length = 10;

// 3,  初始化和声明都加extern也可以。

extern const int length;

extern const int length = 10;

参考:

http://www.c-faq.com/decl/extarraysize.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夜流冰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值