w3resource

How to initialize all elements of an array to the same value in C?


Initialize all elements of an Array to the same value in C


In C, there are several ways to initialize all elements of an array to the same value. However, the language does not provide a direct syntax for setting all elements of an array to a specific value upon declaration. Here are some common methods to achieve this, including using a loop, the memset() function, and compound literals for specific values.

Method 1: Using a Loop

The most common approach is to use a for loop to set each element to the desired value.

Code:

#include <stdio.h> 
int main() {
    int arr[15];
    int value = 5;

    // Initialize all elements to 3 using a loop
    for (int i = 0; i < 15; i++) {
        arr[i] = value;
    }

    // Print the array to confirm initialization
    for (int i = 0; i < 15; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
} 

Output:

5 5 5 5 5 5 5 5 5 5 5 5 5 5 5

Method 2: Using memset (For Zero values)

If you need to initialize an array of integers or characters to zero, you can use the memset function from <string.h>. Note that memset is only suitable for setting values to zero; for non-zero values, a loop is still required.

Code:

#include <stdio.h> 
#include <string.h>

int main() {
    int arr[15];
    
    // Initialize all elements to 0 using memset
    memset(arr, 0, sizeof(arr));

    // Print the array to confirm initialization
    for (int i = 0; i < 15; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}

Output:

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

Method 3: Using designated initializers (For specific values)

This syntax is specific to GNU extensions and may not be available in compilers.

  • In C99 and later, you can use designated initializers to set all elements to a specific value in a shorter array. However, this is limited to small arrays since it requires listing each element explicitly.

    Code:

    #include <stdio.h> 
    int main() {
        int arr[15] = { [0 ... 14] = 9 };  // Initializes all elements to 9
    
        // Print the array to confirm initialization
        for (int i = 0; i < 15; i++) {
            printf("%d ", arr[i]);
        }
        return 0;
    }
    

    Output:

    9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
    

    Summary

    • Loop: Flexible for any value and array size.
    • memset: Works well for zeroing arrays but not for other values.
    • Designated Initializers: Good for small arrays in C99 or later, using syntax like {[0 ... 4] = value}.
  • 

    Follow us on Facebook and Twitter for latest update.