【问题标题】:difference between array and pointer notation of strings in CC中字符串的数组和指针表示法之间的区别
【发布时间】:2013-12-18 13:04:08
【问题描述】:
#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]&amp;heart[i] 表示相同的东西,即heart[i] 的地址,为什么我的程序给我这个-?????? 作为输出?有人可以帮我吗?

【问题讨论】:

  • 你在哪里读到的heart[i]&amp;heart[i]一样?
  • 它们的意思不同。
  • 字符数组的名称与任何数组名称一样,会产生数组第一个元素的地址。因此,以下对数组 m1 成立: m1 == &m1[0] 、 *m1 == 'L' 和 *(m1+1) == m1[1] == 'i' 来自 C Primer Plus-STephen普拉塔,我也很困惑。
  • 是什么让您认为char 与字符的地址相同(char *)?! I've explained this in an answer to one of your other questions,不是吗?
  • 您误读了等价。显然,数组是char m1[] = "Like"; 或类似的东西。说m1 == &amp;m1[0] 是准确的。说*m1 == 'L' 相当于说m1[0] == 'L' 并且鉴于我显示的初始化是准确的。同样,*(m1+1) == 'i'm1[1] == 'i' 分别是准确的,但复合语句 *(m1+1) == m1[1] == 'i' 在 C 中不会计算为 true,尽管松散地说是有道理的。

标签: c arrays string pointers


【解决方案1】:

首先

应该是

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

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

【讨论】:

    【解决方案2】:

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

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

    试试这样的循环:

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

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

    【讨论】:

    • 是的,%p 可以;当然,它会做完全不同的工作。 %p 将打印地址; %s 将打印子字符串。在这两者中,子字符串可能对 OP 来说更有趣,但您可以将 printf("%p\n", (void *)&amp;heart[i]); 添加到信息打印操作列表中。
    • @MarounMaroun: %p 还需要 (void *) 演员表
    猜你喜欢
    • 2015-08-19
    • 2013-12-16
    • 1970-01-01
    • 1970-01-01
    • 2011-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多