C – How to Initialize All Elements of an Array Separately

arraysc++initialization

when we write something like this

int arr[5] = 0; or int arr[5] = {0};

there is no problem

but when we do something like this

int arr[5];
arr[5] = {0};

an error occurs. Any explanation for this ?

Best Answer

It is simply a part of the language definition that arrays can be initialised, but not directly assigned. You can do what you want in C99 using memcpy() with a compound literal:

int arr[5];

/* ... */

memcpy(&arr, &(int [5]){ 0 }, sizeof arr);

With GCC's typeof extension, you can add a little more safety:

memcpy(&arr, &(typeof(arr)){ 0 }, sizeof arr);

In C89 you must give the source array a name:

{ static const int zero[5] = { 0 }; memcpy(&arr, &zero, sizeof arr); }
Related Question