Search code examples
arrayscinitializationassign

Initialize an array in C error "expected expression before ‘]’ token"


When I declare an array like this.

int array[4] = {1, 2, 3, 4};
// do some calculation here with array.
.................
// After that, I set the elements of array as '0' here.
memset(array, 0, sizeof array);

// Right now the elements in array are all '0'.
// I want to initialize the array with different elements.
 array[] = {1, 2, 3, 4};   // I got error here:
 // error: expected expression before ‘{’ token
 // Even I change to array[] = {1, 2, 3, 4}, it still give me same.

Could everyone tell me why I cannot use the same array to re-initialize it like Java. I already clear the array elements as '0' here.

Do I have to name a different array from fresh and initialize it? I cannot use the previous defined array later?

Thank you


Solution

  • You can only "initialize" once. That's why it's called "initialization".

    What you are attempting to do here is assignment, and you have two main problems:

    1. The array is called array, not array[];
    2. Arrays cannot be assigned to.

    You will have to assign the elements one by one, or re-fill the array in batch.

    And Java is entirely irrelevant, as are sunglasses and llamas.