[c] How to set all elements of an array to zero or any same value?

I'm beginner in C and I really need an efficient method to set all elements of an array equal zero or any same value. My array is too long, so I don't want to do it with for loop.

This question is related to c arrays linux

The answer is


If your array has static storage allocation, it is default initialized to zero. However, if the array has automatic storage allocation, then you can simply initialize all its elements to zero using an array initializer list which contains a zero.

// function scope
// this initializes all elements to 0
int arr[4] = {0};
// equivalent to
int arr[4] = {0, 0, 0, 0};

// file scope
int arr[4];
// equivalent to
int arr[4] = {0};

Please note that there is no standard way to initialize the elements of an array to a value other than zero using an initializer list which contains a single element (the value). You must explicitly initialize all elements of the array using the initializer list.

// initialize all elements to 4
int arr[4] = {4, 4, 4, 4};
// equivalent to
int arr[] = {4, 4, 4, 4};

Similar questions with c tag:

Similar questions with arrays tag:

Similar questions with linux tag: