您的位置:首页 > 编程语言 > C语言/C++

c语言中全局变量在不同文件中的引用(一)

2012-08-22 22:43 381 查看
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被认为是外部定义的一个指针变量,但是这个指针变量并没有指向某个对象,所以在运行过程中会出现随机访问内存的情况。
本文出自 “飞翔的云” 博客,请务必保留此出处http://coldcloudy.blog.51cto.com/5797907/970380
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐