Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does direct passage of string to printf correctly works?

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

like image 752
ela Avatar asked Feb 06 '23 17:02

ela


1 Answers

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);
like image 196
dbush Avatar answered Feb 09 '23 05:02

dbush