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:
const char* yo2 = (char [4]) { 'a', 'b', 'c', '\0' };
which is valid and will achieve what you want. Note that it is not equivalent to:
const char* yo2 = "abc":
In the former case, when yo2
is declared at file-scope: the compound literal array has static storage duration but when yo2
is 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:
const char yo2[] = { 'a', 'b', 'c', '\0' };
Regarding your example. In C:
const char* yo2 = { 'a', 'b', 'c', '\0' };
is not valid and your compiler interprets it as:
const char* yo2 = (char *) 'a';
The value of 'a'
is not a pointer value (an address) so dereferencing yo2
invokes undefined behavior.
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