Question

How to Initialize All Elements of an Array to the Same Value in C

carraysinitializationarray-initialize

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:

  1. Initialization: giving an array its first value when it is created.
  2. 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
Take Quiz

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

  1. int numbers[4];

    • An array of 4 integers is created.
    • At this moment, its contents are uninitialized because it is a local array.
  2. for (int i = 0; i < 4; i++)

    • The loop starts with i = 0.
    • It continues while i < 4.
  3. numbers[i] = 3;

    • When i = 0, numbers[0] becomes 3.
    • When i = 1, numbers[1] becomes 3.
    • When i = 2, numbers[2] becomes 3.
    • When i = 3, numbers[3] becomes 3.
  4. 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.

Take Quiz

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:

  • -1 for “not found”
  • NULL for 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

MethodWorks at declaration?Good for zero?Good for non-zero values?Notes
int a[5] = {0};YesYesNoBuilt-in initializer syntax; zero-fills the rest
int a[5] = {7};YesNoNoOnly first element becomes 7
for loopYes/NoYesYesMost general and safest approach
memset(a, 0, sizeof a)NoYesUsually noFills bytes, not logical elements
memset(a, 'A', sizeof a) on char[]NoNot specificallyYesSafe because char is one byte

memset() vs loop

Featurememset()Loop
Operates on bytesYesNo
Operates on array elementsNoYes
Safe for zeroing many typesUsually yesYes
Safe for arbitrary int valuesNoYes
Easy to express “every element = value”Not alwaysYes

Initialization vs assignment

ConceptExampleWhen used
Initializationint a[5] = {0};When the array is created
Assignment after creationa[i] = 7;After the array already exists
Take Quiz

Cheat Sheet

Quick rules

  • int a[5] = {0}; → all elements become 0
  • int a[5] = {7}; → first element is 7, rest are 0
  • Use a for loop to fill an array with any non-zero value
  • memset() fills bytes, not array elements
  • memset(a, 0, sizeof a) is commonly correct for zeroing arrays
  • memset(a, 1, sizeof a) does not mean every int becomes 1

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 or memset(..., 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.

Take Quiz

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

  1. Create one integer array initialized with {0}.
  2. Create one integer array filled with a non-zero value using a loop.
  3. Create one integer array using memset(..., 0, ...).
  4. Print all array contents clearly.
  5. Include one example showing why memset(..., 1, ...) is not the same as setting every integer to 1.
Take Quiz

Keep learning

Related questions

View more