初始化字符串时char []和char *之间的区别:C

时间:2014-06-05 11:55:44

标签: c memory

我读到了这个: Difference between char a[]="string"; char *p="string";

但请考虑以下代码:(我hard coded阅读地址:仅供试用)

#include <stdio.h>

#define read(x,y) *((y*) x)

int main()
{
const char name[]="Andrew";
printf("Printing name : %p\n",name);
printf("Printing &name : %p\n",&name);
printf("At address 0x22ac39:%c\n",read(0x22ac39,char));
printf("At address 0x22ac3a:%c\n",read(0x22ac3a,char));
printf("At address 0x22ac3b:%c\n",read(0x22ac3b,char));
printf("At address 0x22ac3c:%c\n",read(0x22ac3c,char));
printf("At address 0x22ac3d:%c\n",read(0x22ac3d,char));

const char* add="University Of Glasgow";
printf("Printing add :  %p\n",add);
printf("Printing &add : %p\n",&add);
printf("At address 0x402121:%c\n",read(0x402121,char));
printf("At address 0x402122:%c\n",read(0x402122,char));
printf("At address 0x402123:%c\n",read(0x402123,char));
printf("At address 0x402124:%c\n",read(0x402124,char));
printf("At address 0x402125:%c\n",read(0x402125,char));


return 0;
}

输出显示:

$ ./memory.exe
Printing name : 0x22ac39
Printing &name : 0x22ac39
At address 0x22ac39:A
At address 0x22ac3a:n
At address 0x22ac3b:d
At address 0x22ac3c:r
At address 0x22ac3d:e
Printing add :  0x402121
Printing &add : 0x22ac34
At address 0x402121:U
At address 0x402122:n
At address 0x402123:i
At address 0x402124:v
At address 0x402125:e

休息一切都很好,但不能掌握下面的两个陈述,显示相同的内容?

printf("Printing name : %p\n",name);
printf("Printing &name : %p\n",&name);

1 个答案:

答案 0 :(得分:0)

char * 是一个(运行时存储的)指向char(或chars数组)的指针,同时 char [] 是一个chars本身的数组,并且没有指针存储在运行时。

这就是为什么在 char [] 的情况下,第一个字符的地址和数组实例本身的地址是相同的。