Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ Initialise char array to const char*

Say I have a char array, this is ok:

char myChars[100] = "hello";

But if I have a

const char* hello="hello";
char myChars[100] = hello;

or

const char hello[6]="hello";
char myChars[100] = hello;

it's not allowed:

error: array must be initialized with a brace-enclosed intializer

Seems to me that these are basically equivalent statements, why is this the case?

like image 887
jdex Avatar asked Dec 08 '22 19:12

jdex


1 Answers

Because pointers are not arrays, and arrays are not pointers.

These examples are not equivalent; the string literal "hello" is not a pointer, but a const char[6], which may be used to initialise your char myChars[100] as a special case.

However, if you first make it decay to a pointer, you can't get that array-ness back again later. There's no way, in the general case, for the compiler to know how large the array would be, or that it even is one. Thus, initialising an array from a pointer is invalid, no matter what came before.

like image 111
Lightness Races in Orbit Avatar answered Jan 01 '23 01:01

Lightness Races in Orbit