c语言中在某个文件中定义的全局变量可以在不同的文件中引用,对数组和指针这两种全局变量在使用时必须要注意,外部引用格式不正确时会出现编译或运行错误。下面通过不同的例子来说明数组和指针类型全局变量的引用。
一、全局变量为数组
example1:
- test1.c
- int a[10] = {1,2,3,4,5};
- test2.c
- #include <stdio.h>
- #include <stdlib.h>
- extern int a;
- int main()
- {
- printf("%d\n", a[2]);
- return 0;
- }
编译时会出现下面错误,说明在test2中的extern引用的a实际上是一个变量,而不是一个数组,在第10行会出现编译错误。
- error: subscripted value is neither array nor pointer
example2:
- test1.c:
- int a[10] = {1,2,3,4,5};
- test2.c:
- #include <stdio.h>
- #include <stdlib.h>
- extern int a[];
- int main()
- {
- printf("%d\n", a[2]);
- return 0;
- }
此例编译和运行都没有任何问题,运行结果为3。说明extern引用的a就是在test1.c中定义的数组。
example3:
- test1.c:
- int a[10] = {1,2,3,4,5};
- test2.c:
- #include <stdio.h>
- #include <stdlib.h>
- extern int *a;
- int main()
- {
- printf("%d\n", a[2]);
- return 0;
- }
此例在编译时没有任何问题,但是运行时会出现野指针访问错误,因为此处a被认为是外部定义的一个指针变量,但是这个指针变量并没有指向某个对象,所以在运行过程中会出现随机访问内存的情况。
转载于:https://blog.51cto.com/coldcloudy/970380