Koray Tugay
Koray Tugay

Reputation: 23780

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

?

Upvotes: 0

Views: 162

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

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

Upvotes: 9

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

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.

Upvotes: 5

Related Questions