user1323328
user1323328

Reputation: 119

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

Upvotes: 3

Views: 26881

Answers (3)

user2824459
user2824459

Reputation: 11

int array[4] = {1,2,3,4};
//do some calculation 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.
int array2[4] = {1, 2, 3, 4};
memcpy(array, array2, sizeof(array2));

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

Arrays do not have the copy assignment operator and may not use a braced-init list for assigning.

So you have to assign each element of an array individually.

Another approach is to use a structure as a wrapper around an array. In this case you may use the copy assignment operator by means of compound literals.

Here is a demonstrative program

#include <stdio.h>

int main( void )
{
    struct array
    {
        int a[4];
    } myArray = { { 1, 2, 3, 4 } };

    for ( size_t i = 0; i < 4; i++ ) printf( "%d ", myArray.a[i] );
    printf( "\n" );

    myArray = ( struct array ) { { 5, 6, 7, 9 } };

    for ( size_t i = 0; i < 4; i++ ) printf( "%d ", myArray.a[i] );
    printf( "\n" );
}    

Its output is

1 2 3 4 
5 6 7 9

Another advantage of this approach is that you may use such a structure as a return type of functions allowing to return in fact arrays.

Upvotes: 5

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385108

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.

Upvotes: 7

Related Questions