10

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?

1 Answer 1

6

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).

Sign up to request clarification or add additional context in comments.

4 Comments

thanks. is there a way to use the const keyword to make the 1st piece of code work?
@lang2 Not in that scope. See this C FAQ. Not even with char *const hi (constant pointer to char).
Just added something, tho' I'm not sure if it will work... your first version compiles OK in C++ - I'll try with a C compiler when I get a moment :)
@icabod It won't. Read the link I posted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.