简体   繁体   中英

Explain the strange output ''

I have written the code in C language,

#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:
输出

I copied the strange characters on line 1 and 3 of the output and pasting it on the editor gives this " 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.

This invokes Undefined Behavior :

Quote from C18, 7.21.6.1/9 - "The fprintf function":

" 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. "


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. Else you attempt to print the value of the pointer - the address of the object the pointer point to. And due to this operation, you using the wrong conversion specifier of %d instead of %p to print the value of a pointer.


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.

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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