Why doesn’t this work? Is it possible to do some creative casting to get this to work?
1: const char* yo1 = "abc";
2: const char* yo2 = { 'a', 'b', 'c', '\0' }; // <-- why can't i do this?
3: printf("%s %s\n", yo1, yo2);
Result: Segmentation Fault
Line 2 isn’t doing what I expect it to do.
You can do:
which is valid and will achieve what you want. Note that it is not equivalent to:
In the former case, when
yo2is declared at file-scope: the compound literal array has static storage duration but whenyo2is declared at block-scope the compound literal has automatic storage duration.In the latter case,
"abc"is a string literal and has static storage duration (file scope or block scope).You can also use an array instead of a pointer:
Regarding your example. In C:
is not valid and your compiler interprets it as:
The value of
'a'is not a pointer value (an address) so dereferencingyo2invokes undefined behavior.