I know that in C both of these works:
char* string = "foo";
printf("string value: %s", string);
and more simply:
printf("string value: %s", "foo");
But I was asking myself why.
I know that %s
identifier expects the argument to be a char*, and string
actually is (and it will be the same with an array of characters, because this two datatypes are pretty the same in C)
but when I pass directly a string to printf shouldn't it be different? I mean "foo"
is not a pointer anymore... Right?.
The string constant "foo"
has type char []
. When passed to a function, the array decays to a pointer, i.e. char *
. So you can pass it to a function that expects the same.
For the same reason, you can also pass a variable of this type:
char string[4] = "foo";
printf("string value: %s", string);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With