tags:

views:

513

answers:

5

I thought you could declare an array, and then later initilze it.

Like so

char* myArray[3];


//CODE INBETWEEN 

myArray[3] = {

            "blah",
            "blah",
            "blah"};
+9  A: 

Nope, you can only initialize an array when you first declare it. The reason is that arrays are not modifiable lvalues.

In your case:

char *array[] = {"blah", "blah", "blah"};

You don't need to specify the size, but you can if you want. However, the size can't be less than 3 in this case. Also, the three strings are written to read-only memory so something like array[1][2] = 'c' to change the 2nd "blah" to "blch" will normally result in a segfault.

Mike Mu
More precisely, arrays in most contexts evaluate to rvalues, not lvalues, and assignment to an rvalue is not allowed.
caf
Actually, your explanation is probably more correct. Edited my post.
Mike Mu
A: 

You thought wrong. Initialization is only possible at declaration. After that, you can only assign individual values.

DevSolar
A: 

It's an initializer expression. Can't have that code in between, got to be used on the line withe declaration.

djna
+2  A: 

As others have said you can only use initialisers when the variable is declared. The closest way to do what you want is:

char *myArray[3];

/* CODE INBETWEEN */

{
    static const char *tmp[3] = {
            "blah",
            "blah",
            "blah" };
    memcpy(myArray, tmp, sizeof myArray);
}
caf
A: 

Yes, you can declare an array and then later initialize it.
However, there is an exception here.
You are declaring a character pointer array (which worked fine).
And, then you are instantiating constant strings to assign them to the array.

That is where the problem starts.
Constant strings are just compiler primitives that do not get any addressable memory location in the way you have used them. They can be assigned right at the array initialization time (as Mike has shown); that will instruct the compiler to allocate them as constants available at run-time and allow an initialization when the scope of myArray starts.


What you have tried would have worked well with

int numberArray[3];
// code here
numberArray[0] = 1;
numberArray[1] = 2;
numberArray[2] = 3;

It helps to note that a character pointer and a string instance are two different entities; the first can point to the second.

nik
In your example you are not initializing the values. You are simply setting the value. An optimizer may turn what you wrote in to initialization but there is no guarantee.
Jared
@Jared, I'll take your down-vote and comment in the spirit of the exact meaning of `initialization`. However, I do not think the question meant the word in that sense.
nik