【问题标题】:C string dereference and then re-reference acting strangely?C字符串取消引用然后重新引用行为奇怪?
【发布时间】:2019-09-09 14:16:45
【问题描述】:

我有以下代码:

#include <stdio.h>

int main(){
  char *p = "abc";
  char c = *p;
  printf(&c);
  return 0;
}

跑步,我明白了

[OP@localhost test]$ gcc ptr.c
[OP@localhost test]$ ./a.out 
a%QV[OP@localhost test]$ 

我期待它只打印“abc”。为什么会这样?

【问题讨论】:

  • c 是单个字符(仅包含 'a'),因此 &amp;c 不会是一个以 null 结尾的字符串。
  • c的地址(由&amp;c确定)与"abc"的地址(即存储在p中的指针)不同。
  • @lurker 太好了,这就是我的问题的答案。

标签: c pointers printf


【解决方案1】:

char c = *p; 这是对字符串"abc" 中第一个字母的硬拷贝,仅此而已。

因此,您最终对printf 撒谎并告诉它在单个字符c 的地址处,它将找到一个完整的有效格式字符串。

但它只会找到字符a,它根本不是字符串,因为任何地方都没有空终止符。所以任何事情都可能发生,包括程序崩溃或程序打印垃圾。

【讨论】:

    【解决方案2】:

    格式字符串应为以 NUL 结尾的字符序列。

    printf(p) 之所以有效是因为

    • *(p+0) 是 61
    • *(p+1) 是 62
    • *(p+2) 是 63
    • *(p+3) 为 0

    printf(&amp;c) 不起作用,因为

    • *(&amp;c+0) 是 61
    • *(&amp;c+1) 是{未定义的访问行为}

    解决方案 1:

    char *p = "abc";
    char c = *p;
    printf("%c". c);       // a
    

    解决方案 2:

    char *p = "abc";
    char *p2 = *p;         // Copies the pointer
    printf(p2);            // abc
    

    解决方案 3:

    char *p = "abc";
    char *p2 = strdup(p);  // Copies the string (e.g. so you could modify it)
    printf(p2);            // abc
    free(p2);
    

    提示:除非您能保证缺少%,否则printf(p) 通常为wrong。使用printf("%s", p)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-03
      • 1970-01-01
      • 1970-01-01
      • 2015-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多