数组的外部延迟?

Rav*_*pta 24 c

我有一个在文件中定义的数组,在另一个我必须使用它,例如 -

/* a.c - defines an array */

int a[] = {1,2,3,4,5,6,7,8,9}; 


/* b.c - declare and use it. */

#define COUNT ((sizeof a)/(sizeof int))
extern int a[];  //size of array

.
.
.

int i;
for(i=0; i<COUNT; i++)
  printf("%d", a[i]);
.
.
.
Run Code Online (Sandbox Code Playgroud)

现在,当我尝试编译它时,它给了我一个错误,说sizeof不能用于不完整类型.

谁能告诉我如何在C/C++中处理这种情况?我不想在ac中使用数组下标

提前致谢

Mar*_*ins 25

您可以将以下内容放入其中a.c,然后从中进行外设b.c.

在ac:

int a[] = {1, 2, 3};
const int lengthofa = sizeof( a ) / sizeof( a[0] );
Run Code Online (Sandbox Code Playgroud)

然后在bc:

extern int a[];
// the extern (thanks Tim Post) declaration means the actual storage is in another 
// module and fixed up at link time.  The const (thanks Jens Gustedt) prevents it
// from being modified at runtime (and thus rendering it incorrect).
extern const int lengthofa;

void somefunc() {
  int i;
  for ( i = 0; i < lengthofa; i++ )
    printf( "%d\n", a[i] );
}
Run Code Online (Sandbox Code Playgroud)


AnT*_*AnT 16

如果希望您的数组大小可以作为编译时常量访问,那么除了在数组的extern声明中明确指定数组大小之外别无选择

extern int a[9];
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您有责任确保extern声明和定义之间的数组大小一致.您可以使用清单常量,但是您仍然有责任确保{}声明大小和声明大小之间的初始化程序数相同.

如果你不关心将数组大小作为编译时常量,那么你可以做Mark Wilkins在答案中建议的那样.