24

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.

tshepang
  • 12,111
  • 21
  • 91
  • 136
user3610709
  • 241
  • 1
  • 2
  • 3
  • 1
    Just to ask -- did you indeed try using a loop? Often performance anxiety is unfounded. How many elements does your array have? How often will it be initialized? (As discussed in the answers, that will only be necessary if the array elements are to be initialized with a value other than 0.) – Peter - Reinstate Monica May 07 '14 at 09:10
  • 1
    As I understand you wish to set the value to zero or any other NOT ONLY when initialized. If so this is not a duplicate. – Giorgi Gvimradze Apr 25 '19 at 22:36
  • 1
    Should not be closed as a duplicate. The referenced question asks about **initialization**, this one about **setting** which may also apply to an existing array. – Snackoverflow Jan 24 '21 at 21:03

4 Answers4

29

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};
ajay
  • 9,402
  • 8
  • 44
  • 71
13

You could use memset, if you sure about the length.

memset(ptr, 0x00, length)

Sawan
  • 2,152
  • 1
  • 14
  • 14
11
int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }; // All elements of myArray are 5
int myArray[10] = { 0 };    // Will initialize all elements to 0
int myArray[10] = { 5 };    // Will initialize myArray[0] to 5 and other elements to 0
static int myArray[10]; // Will initialize all elements to 0
/************************************************************************************/
int myArray[10];// This will declare and define (allocate memory) but won’t initialize
int i;  // Loop variable
for (i = 0; i < 10; ++i) // Using for loop we are initializing
{
    myArray[i] = 5;
}
/************************************************************************************/
int myArray[10] = {[0 ... 9] = 5}; // This works only in GCC
1

If your array is static or global it's initialized to zero before main() starts. That would be the most efficient option.

Peter - Reinstate Monica
  • 15,048
  • 4
  • 37
  • 62