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:
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:
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.
Code:
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}.