简体   繁体   中英

Why does the printed char change when I use printf with %s and %c?

This is the code I have:

int main(){
    char *p = "koraytugay";
    printf("%s%i byte(s).\n",   "Size of variable p:"       ,sizeof(p));
    printf("%s%i byte(s).\n\n", "Size of what p points to:" ,sizeof(*p));

    char t[] = "koraytugay";
    printf("%s%i byte(s).\n",   "Size of variable t:"       ,sizeof(t));
    printf("%s%i byte(s).\n\n", "Size of what t points to:" ,sizeof(*t));

    printf("%s%c\n",    "Printing p[3]: ",  p[3]);
    printf("%s%c\n",    "Printing t[3]: ",  t[3]);

    printf("%s",*(&p));

}

and the output I get is:

Size of variable p:8 byte(s).
Size of what p points to:1 byte(s).

Size of variable t:11 byte(s).
Size of what t points to:1 byte(s).

Printing p[3]: a
Printing t[3]: a
koraytugay

When I change the last statement to:

printf("%c",*(&p));

The last line printed will be:

6

instead of

koraytugay

But why? I am expecting that it would print

k

?

%c format specifier expects an argumnet of type char .

In your code, *(&p) is of type char * . Using %c to print that leads to undefined behaviour .

Reference: From chapter 7.21.6.1, C11 standard, paragraph 9,

If a conversion specification is invalid, the behavior is undefined. If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

It doesn't print k because it's expecting a char and you passed a char * so probably

printf("%c", **(&p));

will print k .

The type of &p is char ** because it creates a pointer with the address of p , so *(&p) is exactly the same as p , hence to print *(&p) you need the "%s" specifier.

If you use the "%c" specifier with *(&p) it's evaluated as an integer so you can't predict what is going to be printed because it will depend on what is the value stored in the pointer.

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