I thought you could declare an array, and then later initilze it.
Like so
char* myArray[3];
//CODE INBETWEEN
myArray[3] = {
"blah",
"blah",
"blah"};
I thought you could declare an array, and then later initilze it.
Like so
char* myArray[3];
//CODE INBETWEEN
myArray[3] = {
"blah",
"blah",
"blah"};
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.
You thought wrong. Initialization is only possible at declaration. After that, you can only assign individual values.
It's an initializer expression. Can't have that code in between, got to be used on the line withe declaration.
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);
}
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.