我正面临一个问题,如下所述
我有一些C文件
main.c
#include <stdio.h>
#include "header.h"
int main() {
int x = sizeof(a);
printf("size = %d\n", x);
}header.h
#include <stdio.h>
extern int a[];和header.c
#include "header.h"
int a[] = {1, 21, 3};问题1:这个外部声明是正确的吗?
Que 2:如果是,我会得到一个编译错误,因为
main.c: In function ‘main’:
main.c:5:19: error: invalid application of ‘sizeof’ to incomplete type ‘int[]’
int x = sizeof(a);
^发布于 2016-06-03 18:19:22
在main中,由于a中的int声明,编译器知道extern int a[];是header.h的数组。
但它不知道它的大小,因为从中推导出大小的声明(int a[] = {1, 21, 3};)在main.c中不可见,因为它在与main.c完全无关的header.c中;即使header.c不存在(至少如果您删除了虚假的sizeof),您也可以编译main.c。
无法直接从main.c中获取a数组的大小,但是可以在header.c中创建一个函数来告诉您a数组的大小:
header.c
#include "header.h"
int a[] = {1, 21, 3};
int GetSizeofA()
{
return sizeof a;
}header.h
extern int a[];
int GetSizeofA();main.c
#include <stdio.h>
#include "header.h"
int main() {
int x = GetSizeofA();
printf("size = %d\n", x);
}顺便说一句:在header.h中不需要#include <stdio.h>。
https://stackoverflow.com/questions/37611427
复制相似问题