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?

Community
  • 1
  • 1
lang2
  • 11,433
  • 18
  • 83
  • 133

1 Answers1

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

icabod
  • 6,992
  • 25
  • 41
  • 1
    thanks. is there a way to use the const keyword to make the 1st piece of code work? – lang2 Oct 20 '11 at 10:40
  • 1
    @lang2 Not in that scope. See this [C FAQ](http://c-faq.com/ansi/constasconst.html). Not even with `char *const hi` (constant pointer to char). – cnicutar Oct 20 '11 at 10:44
  • 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 Oct 20 '11 at 10:45
  • @icabod It won't. Read the link I posted. – cnicutar Oct 20 '11 at 10:46