【问题标题】:Explain the strange output ''解释奇怪的输出''
【发布时间】:2020-07-24 20:13:36
【问题描述】:

我已经用 C 语言编写了代码,

#include<stdio.h>

int main(void)
{
    char c[]="Suck It Big";
    char *p=c;
    printf("%c\n",p);
    printf("%c\n",p[3]);
    printf("%c\n",++p);
    printf("%d\n",p);
    printf("%d\n",p[3]);
}

我得到的这段代码的输出是:

我在输出的第 1 行和第 3 行复制了奇怪的字符并将其粘贴到编辑器上,得到了“DLE”。谁能解释一下这是什么意思。

【问题讨论】:

  • 您正在尝试将指针打印为char。那是未定义的行为。
  • “DLE”和 ?​​span>
  • 怎么样?这是未定义的行为。试图解释未定义的行为是没有意义的。
  • @kaylum .. 我检查了 DLE 的东西.. 它可能是一个代表 DLE(数据链接转义)的 ascii 字符.. 我认为答案还有更多。

标签: c output ascii non-ascii-characters


【解决方案1】:

您使用的所有printf() 调用都不正确,除了第二个,因为相对参数或使用的转换说明符错误。

这会调用Undefined Behavior:

引自 C18, 7.21.6.1/9 - “fprintf 函数”:

"如果转换规范无效,则行为未定义。288) 如果任何参数不是相应转换规范的正确类型,则行为未定义。"


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

当您尝试打印指针指向的对象的值时,您必须在指针对象之前使用取消引用运算符 (*)。否则,您尝试打印指针的值 - 指针指向的对象的地址。由于此操作,您使用了错误的转换说明符 %d 而不是 %p 来打印指针的值。


修正后的程序是:

#include<stdio.h>

int main(void)
{
    char c[]= "Suck It Big";
    char *p = c;
    printf("%c\n", *p);              // Prints the first element of array c.
    printf("%c\n", p[3]);            // Prints the fourth element of array c
    printf("%c\n", *(++p));          // Prints the second element of array c
    printf("%p\n", (void*) p);       // Prints the address held in p / first element of c.
    printf("%p\n", (void*) &p[3]);   // Prints the address of the fourth element of c.
}

请注意,要使程序符合 C 标准,必须强制转换为 void*

输出:

S
k
u
0x7fff1d3a133d  // Address defined by system
0x7fff1d3a1340  // Address defined by system

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-06
    • 1970-01-01
    • 2016-08-04
    • 2013-01-10
    • 1970-01-01
    • 2013-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多