Course contentsShow
← C
Lesson 396 of 1,2196. Arrays and StringsFree lesson

Assigning values vs initializing arrays

Assigning values vs initializing arrays

What you'll learn: Why arrays must be filled all at once at the start or one-by-one later, and why a simple equals sign won't work for bulk updates.

In C, arrays are like a row of locked lockers. When you first "buy" the lockers (declare the array), you have a one-time opportunity to put items in all of them at once. After that, you have to visit each locker individually to change what’s inside.

The "One-Shot" Initialization

When you declare an array, you can use an initializer list—a comma-separated list of values inside curly braces. This is the only time C allows you to fill the entire array in a single line.

// This is initialization. It works!
int scores[3] = {92, 85, 77}; 

Think of this like a factory setting. The moment the array is created in your computer's memory, those numbers are stamped right into their slots.

The Assignment Trap

A common mistake for beginners is trying to use that same curly-brace syntax later in the code to "reset" the array.

int scores[3];
// ... some code ...
scores = {10, 20, 30}; // ERROR!

This fails because, in C, the name of the array (scores) acts like a permanent signpost pointing to a specific spot in memory. You cannot "assign" a whole list to a signpost. Once the array exists, the only way to change its contents is to target the specific index (the locker number) using the assignment operator.

How to update values later

If you need to change the data after the array has been created, you must do it element-by-element. While this feels tedious compared to the "one-shot" initialization, it gives you precise control over your data.

#include <stdio.h>

int main() {
    // Initializing at the start
    int levels[3] = {1, 2, 3};

    // To update, we must assign to each index individually
    levels[0] = 10;
    levels[1] = 20;
    levels[2] = 30;

    return 0;
}

If you have a very large array, you wouldn't write a hundred lines of code; you would use a for loop to automate those individual assignments. The rule remains the same: initialization is a bulk action at birth, while assignment is a surgical action performed one piece at a time.

Key takeaway

You can only use {} to fill an array at the moment of declaration; afterward, you must assign values to each index individually.