更改外部变量的值

Luv*_*Luv 3 c extern

我们在File1.c中

int arr[10];
Run Code Online (Sandbox Code Playgroud)

在File2.c中

extern int *arr;

int main()

{
   arr[0]=10;
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

这有什么问题可以解决?为什么?

Jon*_*ler 11

数组不是指针.内存访问将是错误的.

File1.c,你有内存布局:

+---+---+---+---+---+---+---+---+---+---+
+ 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
+---+---+---+---+---+---+---+---+---+---+
^
arr
Run Code Online (Sandbox Code Playgroud)

File2.c,你告诉编译器你有内存布局:

+-------+
|  ptr  |
+-------+
^
arr
Run Code Online (Sandbox Code Playgroud)

指针可能指向可以存储整数的地方.

编译器必须做的事情完全不同的访问extern int *arr;extern int arr[];.

如上所述,最可能的结果是崩溃,因为编译器取消引用空指针.但是,行为是未定义的,任何事情都是可能的.你骗了编译器; 编译器会自己回来 - 它不喜欢被骗.