C中字符串的数组和指针表示法之间的区别

时间:2013-12-18 13:04:08

标签: c arrays string pointers

#include<stdio.h>
int main(void)
{

 char heart[]="I Love Tillie"; /* using array notation */

 int i;
 for (i=0;i<6;i++)
 {
   printf("%c",&heart[i]);  /* %c expects the address of the character we want to print     */
 }

 return 0;

}

如果heart[i]&heart[i]表示相同的事情,即heart[i]的地址,为什么我的程序会将此作为输出???????给我?有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:4)

首先

应该是

printf("%c",heart[i]); // if you want to print the charachter

printf("%p",&heart[i]); // if you want to print the charachter address in the memory

而不是

printf("%c",&heart[i])

heart是一系列字符,heart[i]是数组中的字符数i

&heart[i]i数组中元素编号heart的内存地址。并打印您必须使用的内存地址"%p"

答案 1 :(得分:2)

您正在尝试将地址打印为单个字符;这是坏消息。

heart[i]是一个单一字符; &heart[i]是该角色的地址。它们根本不是一回事。

尝试这样的循环:

for (i = 0; i < 6; i++)
{
     printf("%c", heart[i]);
     printf(": %s\n", &heart[i]);
}

了解不同转换规范(和参数类型)的不同之处。如果您愿意,可以在循环开始时添加printf("%p ", (void *)&heart[i]);,以查看在循环过程中地址值的变化情况。