指针和数组错用的问题汇总

指针和数组名容易用错,本文记录常见的错误。

错误用法一、定义时是数组,在其他文件中声明为指针。

file a.c 中,定义b是一个数值:

 1 #include <stdio.h>
 2 
 3 char b[4] = {'1', '2', '3', '4'};
 4 
 5 void printinfilea(void)
 6 {
 7     printf("in a.c, b=0x%x, first addr=0x%x \n", b, &b[0]);
 8 
 9     return;
10 }

文件 b.c 中声明b为指针:

#include <stdio.h>

extern char *b;

void printinfileb(void)
{
    printf("in b.c, b=0x%x \n", b);

    return;
}

文件 main.c 

 1 #include <stdio.h>
 2 
 3 
 4 int main()
 5 {
 6     printinfilea();
 7     printinfileb();
 8     
 9     return 0;
10 }


在cygwin中运行结果如下:

h@he-c9c1ddb921eb ~/test/ptr-array
$ gcc -mbig -o test  a.c b.c main.c
$ ./test
in a.c, b=0x402000, first addr=0x402000
in b.c, b=0x34333231

总结一下:

在a.c中定义的数组,其数组名(b)只是一个名字,不占用物理的内存区域,只是编译、运行时代表数组的起始地址;

而在b.c中认为b是一个全局变量,指针类型的全局变量,所以,打印b的值,就是打印指针变量中存储的值,所以,就是字符'1','2','3','4'组成的数字。

其实,如果在b.c中打印 &b的值(printf("in b.c, b=0x%x &b=0x%x\n", b, &b);),得到的数值也是0x402000, 如下:

h@he-c9c1ddb921eb ~/test/ptr-array
$ ./test
in a.c, b=0x402000, first addr=0x402000
in b.c, b=0x34333231 &b=0x402000

问题解决、规避方法:

在头文件 a.h 中对外声明 extern char b[], 其他源文件,凡是需要使用b的,只能包含头文件a.h ,不允许显式的extern ...

原文地址:https://www.cnblogs.com/zhouhaibing/p/2923013.html