Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't char pointers be defined as arrays?

Simple question. I am aware I should just be using std::string, but am curious why this works:

const char* example = "test";

while this results in "too many initializer values" on the second character?

const char* example = {0x74, 0x65, 0x73, 0x74, 0x00};

Shouldn't these two things be exactly equivalent?

like image 224
tomysshadow Avatar asked Jun 08 '26 23:06

tomysshadow


2 Answers

The difference is that string literals are arrays all of their own. "test" is used here not as an initializer of an array (a special case where it would be equivalent to { 't', 'e', 's', 't', '\0' }), but the same way as any other value would be.

In other words, when you use a string literal "test" in your code, the compiler automatically creates something like

static const char __str_literal0[] = {'t', 'e', 's', 't', '\0'};

and then

const char *example = "test";

is compiled as if it were

const char *example = __str_literal0;

i.e. it simply points to the (already existing, static) char array.

On the other hand, if you try to use an initializer list, the compiler will set the first field of your variable (that's just example itself) to the first value in the initializer list (example = 0x74), and then complain that you have too many initializers in your list.

like image 182
melpomene Avatar answered Jun 11 '26 13:06

melpomene


Shouldn't these two things be exactly equivalent?

In your second example you are trying to initialize a pointer using copy-list initialization, which is quite far in terms of equivalency from your first example.

Otherwise (if T is not a class type), if the braced-init-list has only one element and either T isn't a reference type or is a reference type that is compatible with the type of the element, T is direct-initialized (in direct-list-initialization) or copy-initialized (in copy-list-initialization), except that narrowing conversions are not allowed.

Even if you supply only one element:

const char* example = {0x74};

to stop compiler complaining about the number of arguments, it is still an error because for a valid copy-initialization you need to supply a pointer and not an int.

char a = 'c';
const char* example = {&a};
like image 40
Killzone Kid Avatar answered Jun 11 '26 15:06

Killzone Kid