Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting initializers down to a pointer

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.

like image 454
user2077309 Avatar asked Feb 15 '13 23:02

user2077309


1 Answers

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.

like image 191
ouah Avatar answered Sep 29 '22 07:09

ouah