简体   繁体   English

解释奇怪的output''

[英]Explain the strange output ''

I have written the code in C language,我用 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]);
}

The output to this code i get is:我得到的这个代码的 output 是:
输出

I copied the strange characters on line 1 and 3 of the output and pasting it on the editor gives this " DLE ".我复制了 output 的第 1 行和第 3 行的奇怪字符并将其粘贴到编辑器上,得到了这个“ DLE ”。 Can anybody explain the meaning of this.任何人都可以解释这个的含义。

All printf() calls you use are incorrect, except for the second one, because either the relative argument or the used conversion specifier is wrong.您使用的所有printf()调用都是不正确的,除了第二个,因为相对参数或使用的转换说明符是错误的。

This invokes Undefined Behavior :这会调用未定义的行为

Quote from C18, 7.21.6.1/9 - "The fprintf function":引自 C18, 7.21.6.1/9 - “fprintf 函数”:

" If a conversion specification is invalid, the behavior is undefined.288) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined. " 如果转换规范无效,则行为未定义。288) 如果任何参数不是相应转换规范的正确类型,则行为未定义。


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

When you attempt to print the value of the object the pointer points to, you have to use the dereference operator ( * ) preceding the pointer object.当您尝试打印指针指向的 object 的值时,您必须在指针 object 之前使用取消引用运算符 ( * )。 Else you attempt to print the value of the pointer - the address of the object the pointer point to.否则,您尝试打印指针的值 - 指针指向的 object 的地址。 And due to this operation, you using the wrong conversion specifier of %d instead of %p to print the value of a pointer.由于此操作,您使用错误的转换说明符%d而不是%p来打印指针的值。


The corrected program is:更正后的程序是:

#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.
}

Note, that the cast to void* is necessary to make the program conforming to the C standard.请注意,要使程序符合 C 标准,必须强制转换为void*

Output: Output:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM