Question
How to Initialize All Elements of an Array to the Same Value in C
Question
I have a large array in C, and I want to set every element to the same value.
I know I could use memset() in some cases, but I am wondering whether C has built-in syntax for initializing every array element to one identical value.
For example, I want to understand the correct and idiomatic ways to do this in C, and when memset() is safe or unsafe to use.
Short Answer
By the end of this page, you will understand how array initialization works in C, when you can use initializer syntax, when you need a loop, and when memset() is appropriate. You will also learn an important rule: memset() works reliably for setting bytes, but not for assigning arbitrary numeric values to array elements.
Concept
In C, there are two related but different ideas:
- Initialization: giving an array its first value when it is created.
- Assignment/resetting: changing all elements after the array already exists.
These are often confused, but C treats them differently.
1. Initializing an array at declaration time
C lets you initialize arrays when you declare them.
int a[5] = {0};
This sets the first element to 0, and because the remaining elements are not explicitly given, C initializes the rest to 0 as well.
So the whole array becomes:
{0, 0, 0, 0, 0}
This is a built-in C feature, but it is mainly useful for zero-initialization.
2. Setting all elements to the same non-zero value
C does not have general built-in syntax like “fill this whole array with 7” for normal arrays.
For example, this does not mean what many beginners expect:
int a[5] = {7};
It produces:
{7, 0, 0, 0, 0}
Only the first element is 7; the rest become 0.
If you want every element to be 7, the standard and correct approach is usually a loop.
3. Where memset() fits in
memset() fills memory byte by byte, not element by element.
memset(a, 0, sizeof a);
This is great for setting all bytes to zero, which commonly gives you an array of zero values.
But this is not safe for arbitrary values:
memset(a, 1, sizeof a); // usually NOT the same as setting every int to 1
If int is 4 bytes, each byte becomes 0x01, so each integer becomes something like:
0x01010101
which is not the integer value 1.
Why this matters
This distinction matters constantly in real C programs:
- clearing buffers
- resetting counters
- preparing lookup tables
- initializing flags
- working with structs and arrays
- avoiding subtle bugs caused by byte-level memory functions
A beginner who understands the difference between initialization, assignment, and byte filling avoids many common C bugs.
Mental Model
Think of an array as a row of storage boxes.
- C initializer syntax is like setting box contents when the boxes are first delivered.
- A loop is like walking box to box and placing the same item in each one.
memset()is like spraying every byte with the same paint color.
That last one is important: memset() does not know what an int, float, or struct means. It only sees raw bytes.
So:
- If you want every byte to become
0,memset()is perfect. - If you want every array element to become the numeric value
5, use a loop.
In short:
- Initializer = setup at creation
- Loop = assign values by element
memset()= fill raw bytes
Syntax and Examples
Zero-initialize an array at declaration
int numbers[5] = {0};
This makes all elements zero.
// Result: {0, 0, 0, 0, 0}
Why it works
In C, if you provide fewer initializers than the array size, the remaining elements are initialized to zero.
Important: {value} does not fill the whole array
int numbers[5] = {7};
This means:
// Result: {7, 0, 0, 0, 0}
Only the first element is explicitly set to 7.
Set all elements after declaration using a loop
int numbers[5];
for (int i = 0; i < 5; i++) {
numbers[i] = 7;
}
This is the standard way to set every element to the same non-zero value.
Use memset() only when byte filling is correct
#include <string.h>
int numbers[5];
memset(numbers, 0, sizeof numbers);
This is commonly used to set the whole array to zero.
Example with char
For a char array, memset() is often fine for many values because each element is one byte:
char buffer[10];
memset(buffer, 'A', sizeof buffer);
This fills the array with 'A' characters.
Example: wrong use of memset() with int
int numbers[4];
memset(numbers, 1, sizeof numbers);
This does not set each element to 1.
It sets every byte to 0x01, which gives unexpected integer values on most systems.
A reusable fill function
void fill_int_array(int arr[], int size, int value) {
for (int i = 0; i < size; i++) {
arr[i] = value;
}
}
Usage:
int numbers[5];
fill_int_array(numbers, 5, 42);
Step by Step Execution
Consider this example:
#include <stdio.h>
int main(void) {
int numbers[4];
for (int i = 0; i < 4; i++) {
numbers[i] = 3;
}
for (int i = 0; i < 4; i++) {
printf("%d ", numbers[i]);
}
return 0;
}
Step by step
-
int numbers[4];- An array of 4 integers is created.
- At this moment, its contents are uninitialized because it is a local array.
-
for (int i = 0; i < 4; i++)- The loop starts with
i = 0. - It continues while
i < 4.
- The loop starts with
-
numbers[i] = 3;- When
i = 0,numbers[0]becomes3. - When
i = 1,numbers[1]becomes3. - When
i = 2,numbers[2]becomes3. - When
i = 3,numbers[3]becomes3.
- When
-
The second loop prints each element.
Final array contents
{3, 3, 3, 3}
Output
3 3 3 3
This is the safest mental pattern for filling an array with any element value.
Real World Use Cases
Common situations
Resetting counters
int counters[100];
memset(counters, 0, sizeof counters);
Used when starting a new calculation or request.
Preparing a flag array
int visited[1000];
for (int i = 0; i < 1000; i++) {
visited[i] = -1;
}
Useful when -1 means “unknown” or “not processed yet”.
Filling a text buffer
char line[80];
memset(line, '-', sizeof line);
Useful for separators, placeholders, or simple formatting.
Initializing lookup tables
int table[256];
for (int i = 0; i < 256; i++) {
table[i] = 42;
}
Used when every entry starts with a default value.
Clearing working memory in embedded systems
In embedded C, arrays often represent device state, sensor history, or communication buffers. Zeroing them quickly is common, but non-zero fills usually still require loops.
Real Codebase Usage
In real projects, developers usually choose the method based on the value and the data type.
Typical patterns
1. Zero-initialize at declaration
int counts[256] = {0};
Common when the array is created and should start empty.
2. Reset existing memory with memset()
memset(counts, 0, sizeof counts);
Common in parsing, networking, and systems code.
3. Use loops for non-zero defaults
for (int i = 0; i < MAX_USERS; i++) {
scores[i] = -1;
}
Common for sentinel values like:
-1for “not found”NULLfor pointer arrays- specific enum values for state arrays
4. Wrap repeated logic in helper functions
void reset_scores(int scores[], int size) {
for (int i = 0; i < size; i++) {
scores[i] = -1;
}
}
This improves readability and avoids duplicated loops.
5. Guarding against size mistakes
Developers often prefer:
memset(arr, 0, sizeof arr);
instead of manually computing byte counts, because sizeof arr stays correct when the array size changes.
Related coding habits
- Use loops when meaning matters at the element level.
- Use
memset()when you truly want byte-level zeroing. - Prefer named constants for default values.
- Encapsulate repeated fill patterns in utility functions.
Common Mistakes
1. Thinking {5} fills the whole array with 5
Broken expectation:
int a[4] = {5};
Actual result:
{5, 0, 0, 0}
How to avoid it
Use a loop for non-zero fill values.
for (int i = 0; i < 4; i++) {
a[i] = 5;
}
2. Using memset() for non-zero integers
Broken code:
int a[4];
memset(a, 1, sizeof a);
This fills bytes, not int values.
How to avoid it
Use a loop unless the value is byte-safe for the target type.
for (int i = 0; i < 4; i++) {
a[i] = 1;
}
3. Forgetting to include <string.h> for memset()
Broken code:
memset(a, 0, sizeof a);
How to avoid it
Include the proper header:
#include <string.h>
4. Using sizeof on a pointer instead of an array
Broken code:
void clear_array(int *arr) {
memset(arr, 0, sizeof arr);
}
Here, sizeof arr is the size of the pointer, not the whole array.
Better approach
Pass the element count:
void clear_array(int *arr, int size) {
memset(arr, 0, size * sizeof *arr);
}
5. Reading uninitialized local arrays
Broken code:
int a[5];
printf("%d\n", a[0]);
Local arrays are not automatically initialized.
How to avoid it
Initialize them explicitly:
int a[5] = {0};
or
memset(a, 0, sizeof a);
Comparisons
Ways to set array values in C
| Method | Works at declaration? | Good for zero? | Good for non-zero values? | Notes |
|---|---|---|---|---|
int a[5] = {0}; | Yes | Yes | No | Built-in initializer syntax; zero-fills the rest |
int a[5] = {7}; | Yes | No | No | Only first element becomes 7 |
for loop | Yes/No | Yes | Yes | Most general and safest approach |
memset(a, 0, sizeof a) | No | Yes | Usually no | Fills bytes, not logical elements |
memset(a, 'A', sizeof a) on char[] | No | Not specifically | Yes | Safe because char is one byte |
memset() vs loop
| Feature | memset() | Loop |
|---|---|---|
| Operates on bytes | Yes | No |
| Operates on array elements | No | Yes |
| Safe for zeroing many types | Usually yes | Yes |
Safe for arbitrary int values | No | Yes |
| Easy to express “every element = value” | Not always | Yes |
Initialization vs assignment
| Concept | Example | When used |
|---|---|---|
| Initialization | int a[5] = {0}; | When the array is created |
| Assignment after creation | a[i] = 7; | After the array already exists |
Cheat Sheet
Quick rules
int a[5] = {0};→ all elements become0int a[5] = {7};→ first element is7, rest are0- Use a
forloop to fill an array with any non-zero value memset()fills bytes, not array elementsmemset(a, 0, sizeof a)is commonly correct for zeroing arraysmemset(a, 1, sizeof a)does not mean everyintbecomes1
Common syntax
int a[10] = {0};
for (int i = 0; i < 10; i++) {
a[i] = 5;
}
memset(a, 0, sizeof a);
Safe rule of thumb
- Want all zeros? Use
{0}at declaration ormemset(..., 0, ...) - Want any other value? Use a loop
Pointer warning
Inside a function parameter like int *a, this is wrong:
sizeof a
because it gives the pointer size, not the array size.
Include for memset()
#include <string.h>
FAQ
Is there built-in C syntax to set every array element to the same value?
Only for the special case of zero-initialization using something like int a[10] = {0};. For arbitrary values, standard C typically uses a loop.
Does int a[10] = {1}; make all elements equal to 1?
No. It makes the first element 1 and the rest 0.
When is memset() safe for arrays?
It is safe when you want to fill raw bytes, especially with 0, or when working with char arrays. It is not the right choice for setting each int or double to an arbitrary value.
Why does memset(arr, 1, sizeof arr) not set all integers to 1?
Because memset() writes the byte value 0x01 into every byte, not the integer value 1 into every array element.
What is the best way to fill an int array with -1?
Use a loop:
for (int i = 0; i < size; i++) {
arr[i] = -1;
}
Is zero-initialization guaranteed with {0}?
Yes. For array initialization, unspecified elements are initialized to zero.
Should I prefer a loop or memset() in C?
Use a loop when you care about element values. Use memset() when you intentionally want byte-level filling, especially zeroing memory.
Mini Project
Description
Build a small C program that demonstrates the three main ways developers try to fill arrays: zero-initialization with declaration syntax, filling with a loop, and byte-filling with memset(). This helps you see the difference between element-based assignment and byte-based memory operations.
Goal
Create a program that initializes arrays in different ways and prints the results so you can compare them.
Requirements
- Create one integer array initialized with
{0}. - Create one integer array filled with a non-zero value using a loop.
- Create one integer array using
memset(..., 0, ...). - Print all array contents clearly.
- Include one example showing why
memset(..., 1, ...)is not the same as setting every integer to1.
Keep learning
Related questions
2D Array Loop Order and Cache Performance in C
Learn why swapping nested loops changes 2D array performance in C, using row-major memory layout, cache locality, and practical benchmarks.
Array-to-Pointer Conversion in C and C++ Explained
Learn what array-to-pointer conversion means in C and C++, how array decay works, and how it differs from a pointer to an array.
Building More Fault-Tolerant Embedded C++ Applications for Radiation-Prone ARM Systems
Learn practical C++ and compile-time techniques to reduce soft-error damage in embedded ARM systems exposed to radiation.