Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string array initialisation

This is a continuation of another question I have.

Consider the following code:

char *hi = "hello";

char *array1[3] = 
{
    hi,
    "world",
    "there."
};

It doesn't compile to my surprise (apparently I don't know C syntax as well as I thought) and generates the following error:

  error: initializer element is not constant

If I change the char* into char[] it compiles fine:

char hi[] = "hello";

char *array1[3] = 
{
    hi,
    "world",
    "there."
};

Can somebody explain to me why?

like image 267
lang2 Avatar asked Oct 20 '11 10:10

lang2


1 Answers

In the first example (char *hi = "hello";), you are creating a non-const pointer which is initialized to point to the static const string "hello". This pointer could, in theory, point at anything you like.

In the second example (char hi[] = "hello";) you are specifically defining an array, not a pointer, so the address it references is non-modifiable. Note that an array can be thought of as a non-modifiable pointer to a specific block of memory.

Your first example actually compiles without issue in C++ (my compiler, at least).

like image 184
icabod Avatar answered Oct 21 '22 22:10

icabod