Initialization occurs only once when you create an array:
int foo[] = {0,1,2,3,4};
After defining the array, you can assign individual elements:
foo[0] = 5; foo[1] = 4; foo[2] = 3; foo[3] = 2; foo[4] = 1;
but you cannot assign to the array itself; IOW, you cannot write something like
foo = {5,4,3,2,1};
However, you can use memcpy to copy the contents of one array to another:
int foo[5]; int bar[5] = {1,2,3,4,5}; int i; memcpy(foo, bar, sizeof bar); // Copies *contents* of bar to foo for (i = 0; i < sizeof foo / sizeof *foo; i++) printf("foo[%d] = %d\n", i, foo[i]);
Likewise, an array created in this way cannot be modified; its size is fixed during the announcement. In C89 and earlier, the size of the array must be known at compile time β either by specifying a size with a compile-time constant (an integral expression or a macro that has been expanded to an integral expression), or using an initializer, such as the one above, from which the size of the array is calculated.
C99 introduced variable-length arrays that can be declared using a run-time value, for example:
void foo(int x) { int arr[x]; ... }
Please note that, like regular arrays, VLAs cannot be modified after they are defined.
Alternatively, you can dynamically allocate an array using malloc , although you cannot initialize it as follows:
int *foo = malloc(sizeof *foo * N);
You can still assign to individual elements:
foo[0] = 5; foo[1] = 4; foo[2] = 3; ...
or you can use memcpy as shown above. Note that you must remember the free array when you are done:
free(foo);
Arrays created in this way can be modified using realloc :
int *tmp = realloc(foo, sizeof *foo * NEW_NUMBER_OF_ELEMENTS); if (tmp) foo = tmp;
Why not just assign the realloc result back to foo ? If the realloc operation failed, it will return NULL. If this happens, and we return the result back to foo , we will lose the memory of the already allocated memory, which will lead to a memory leak.
C99 introduced array literal syntax; you can write something like
int *foo = (int[]){1,2,3,4,5};
and then index in foo as an array:
printf("foo[%d] = %d\n", i, foo[i]);
although I'm sure you cannot change the contents of foo[i] , much like trying to change the contents of a string literal undefined (although I did not find a chapter and a verse on this).