Pointer cast initializers

Why is this not working? Is it possible to do some kind of creative casting to make it 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 error

Line 2 does not do what I expect from her.

+5
source share
1 answer

You can do:

const char* yo2 = (char [4]) { 'a', 'b', 'c', '\0' };

which is valid and will achieve what you want. Note that this is not equivalent:

const char* yo2 = "abc":

In the first case, when yo2declared in a file area: an array of compound literals has a static storage duration, but when yo2declared in a block area, a composite literal has an automatic storage duration.

"abc" ( ).

:

 const char yo2[] = { 'a', 'b', 'c', '\0' };

. C:

const char* yo2 = { 'a', 'b', 'c', '\0' };

, :

const char* yo2 = (char *) 'a';

'a' (), yo2 undefined.

+5

All Articles