【问题标题】:Explanation regarding character pointer for string关于字符串的字符指针的说明
【发布时间】:2016-05-18 21:46:57
【问题描述】:

您好,我是编程新手。 在下面的代码中str 是一个指向字符的指针,所以str 应该包含字符'h' 的地址。因此应使用 %p 打印该地址。但我不明白 %s 是如何用于打印指针参数的。

    #include<stdio.h>

    int main (){
    char s[] = "hello";
    char *str = s;
    int a[] = {1, 2, 3, 4, 5};
    int *b = a;
    printf("%s\n", str);        // I don't understand how this works ? 
    printf("%c\n", *str);       // This statement makes sense
    printf("%c\n", *(str + 1)); // This statement also makes sense.
    printf("%p\n",str);         // This prints the address of the pointer str. This too makes sense.
    printf("%d\n",*b);          // makes sense, is the same as the second print.
    //      printf("%d",b);     // I don't understand why str pointer works but this gives a compile error
    return 0;
}

【问题讨论】:

  • 什么不清楚?为什么字符串格式说明符适用于字符串?因为它被定义为工作......
  • 我无法理解第一次打印。我认为如果第一次打印有效,评论中的最后一次打印也应该有效,但那不是真的,所以这就是我的问题,谢谢。
  • 为什么printf("%d", b);不应该给出错误?
  • @user6353278 你到底有什么不明白的? str 是一个数组 hello 怎么会被打印出来?
  • %s 表示:检索 char* 参数。取消引用指针并打印字符和后续字符,直到遇到 \0

标签: c arrays string pointers character


【解决方案1】:
char s[] = "hello";

声明一个以零结尾的字符数组,称为 s。和写作一样

char s[6] = { 'h', 'e', 'l', 'l', 'o', '\0' };

如您所见,引号是一种简写形式。


char *str = s;

这将str 声明为指向字符的指针。然后它使str 指向s 中的第一个字符。也就是说str包含s中第一个字符的地址。


int a[] = {1, 2, 3, 4, 5};

声明一个整数数组。它将它们初始化为值 1-5,包括 1-5。


int *b = a;

声明 b 是一个指向 int 的指针。然后它使b 指向a 中的第一个int。


printf("%s\n", str);

%s 说明符接受字符串中第一个字符的地址。 printf 然后从那个地址走出来,打印它看到的字符,直到它看到末尾的 \0 字符。


printf("%c\n", *str);

这将打印str 中的第一个字符。由于str 指向一个字符(字符串中的第一个字符),那么*str 应该获取指向的字符(字符串中的第一个字符)。


printf("%c\n", *(str + 1));

这将打印str 中的第二个字符。这是写str[1] 的漫长道路。这背后的逻辑是指针运算。如果str 是一个字符的地址,那么str + 1 是数组中下一个字符的地址。由于(str + 1) 是一个地址,它可能会被取消引用。因此,* 获得了数组第一个字符之后的第 1 个字符。


printf("%p\n",str);

%p 说明符需要一个指针,就像 %s 一样,但它做了其他事情。它不是打印字符串的内容,而是简单地以十六进制打印指针所包含的地址。


printf("%d\n",*b);

这将打印b 指向的数组中的第一个int。这相当于写b[0]


printf("%d",b);

bint *,而不是 int,这是 %d 所期望的。如果您尝试打印数组第一个元素的地址,则说明符将是%p,而不是%d。此外,此行不应生成编译器错误。相反,它应该是运行时未定义的行为,因为编译器不知道printf 格式字符串是什么。

【讨论】:

  • printf("%c\n", *str); 打印第一个字符。 *str*(str + 0)); 的简化结果(显然 + 0 什么都不做)。 `
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-21
  • 2020-03-22
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
相关资源
最近更新 更多