C 外部数组,如何使用

C 外部数组,如何使用,c,segmentation-fault,extern,C,Segmentation Fault,Extern,我想使用外部字符数组,比如大小为50 我有外行 extern char arr[50]; 我有一个空调,在那里我正在访问arr 我有个b.c,那是我的驱动程序文件 此外,我还有一个a.h,在a.c.中有函数的定义 现在在我的驱动程序文件b.c中 #include"extern.h" #include"a.h" char arr[50]; int main() { //call to function in a.c } 在我的空调里我有 #include"a.h" #include"exter

我想使用外部字符数组,比如大小为50

我有外行

extern char arr[50];
我有一个空调,在那里我正在访问
arr

我有个b.c,那是我的驱动程序文件

此外,我还有一个a.h,在a.c.中有函数的定义

现在在我的驱动程序文件b.c中

#include"extern.h"
#include"a.h"
char arr[50];
int main()
{
//call to function in a.c
}
在我的空调里我有

#include"a.h"
#include"extern.h"
int function1()
{
//accessing arr, say printing arr[1]
}
这给了我seg故障

我是否包括文件权,以及我在extern.h和b.c中对外部变量的声明是否正确


seg故障的原因是什么?

您使用extern的方式没有问题

如果b.c中的extern声明将隐藏
字符arr[50]声明,则会出现链接错误

extern char arr[50];
char arr[50];
int main() {
  //call to function in a.c
}
问题一定在别处。也许是printf的使用方式


不要在b.c(main())中包含extern.h:arr[]定义为“两次”,一次包含extern,另一次不包含extern。。。extern赢了,所以arr[]不是静态地与分配的数组相关联。@为什么“extern赢了”?数组声明“wins”,否则将出现链接错误。问题一定出在别处(如printf使用不当)。
printf("%c\n", arr[1]);  // works
printf("%s\n", &arr[1]); // may cause a seg fault depending on arr content