What are Initialize Arrays in C- Free Embedded C Programming Course

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

Free C Programming Course · Arrays · Lecture 6

Initialize Arrays in C

Learn how to initialize array in C the right way: garbage versus zero, partial lists, designated slots and safe copying, with tested programs for embedded targets.

6
Arrays chapter
12 min
Read and practise
100%
Free forever

Welcome to another lecture of our free C programming course from EmbeddedPathashala. Today we learn how to initialize array in C, and more importantly what an array contains when you do not.

This free C tutorial is written for students who want to work in firmware. Each rule is shown with a small program, the exact build command and the real output, so you can follow along on any Linux laptop.

What You Will Learn

  • Why local arrays contain garbage while static and global arrays are zero
  • Full, partial, size-omitted and designated array initializers
  • The {0} zero-fill idiom and its limits
  • Why b = a does not copy an array and how to copy correctly
  • How startup code initializes arrays on a microcontroller

Prerequisites

  • Lectures 1 to 5 of this arrays chapter (declaring and accessing a 1-D array)
  • A working GCC or Clang compiler
  • Basic knowledge of for loops and printf()

Why Array Initialization in C Matters for Embedded Code

Every embedded program owns a few arrays: a UART receive buffer, a table of ADC calibration values, a list of GPIO pin numbers, a window of sensor samples. The moment you declare one, a block of memory is reserved for it, and that memory already contains something. What that something is depends on where the array lives. If you do not know the rule, your first bug will be a buffer that works on your desk and fails on the customer’s board. This lecture shows the exact rules for initialize array in C, one by one, with programs you can compile and run today.

Default Values: Garbage or Zero?

C gives different guarantees depending on the storage duration of the array. Memorise the table below, it explains most of the strange array bugs beginners meet. Whenever you initialize array in C code, ask which row of the table applies to your declaration.

Where the array is declaredStorageValue before you writeSafe to read?
Inside a function, no staticStack (automatic)Indeterminate, whatever was left on the stackNo, write first
Inside a function with staticStatic data (.bss)All zeroYes
Outside every function (file scope)Static data (.bss)All zeroYes
Any array with an initializer listDepends on locationYour values, remaining slots zeroYes

Where C arrays live in a typical microcontroller

Flash.text / .rodataconst tables, code
RAM.dataarrays with non-zero initializers
RAM.bssfile-scope and static arrays, zeroed
RAMstacklocal arrays, uninitialized

On a PC the operating system hands your program zeroed memory, so a static array is zero. On a bare-metal MCU nobody does that for you. The startup code that runs before main() does it: it copies the initial values of .data from flash into RAM and fills .bss with zeros. That is why the C guarantee holds even without an operating system, and why a large initialized array costs flash space as well as RAM.

Warning: a local array such as int buf[8]; is not zero. Reading buf[3] before writing it is a bug, and the compiler is allowed to treat it as undefined behaviour. The program may print 0 today and a random number tomorrow.

Four Ways to Initialize an Array in C

There are four forms. Each one is a different way to initialize array in C, and each has a use.

1. Full initializer list

Give one constant per element, separated by commas, inside braces. The values are assigned in order starting at index 0.

int volts[5] = {33, 50, 12, 18, 5};   /* volts[0]=33 ... volts[4]=5 */

2. Let the compiler count the size

If you leave the brackets empty, the compiler sizes the array to match the number of initializers. This is the best way to write lookup tables because you can add a value without updating a number.

int inferred[] = {10, 20, 30, 40, 50, 60};   /* 6 elements */
size_t n = sizeof inferred / sizeof inferred[0];     /* element count idiom */

3. Partial initialization fills the rest with zero

Fewer values than elements is legal. The values you gave go to the first slots and every remaining slot becomes zero, not garbage. This even applies to a local array.

int partial[6] = {7, 3};

index[0][1][2][3][4][5]
value730000
set byyouyoucompilercompilercompilercompiler

4. The zero-fill idiom and designated initializers

Writing {0} gives the first element the value 0 and, by the partial-initialization rule, all the others too. Since C99 you can also name the slots you care about with [index] = value. Unnamed slots become zero, and if you omit the size the array becomes as long as the highest index plus one.

#include <stdio.h>

int g_table[4];                      /* file scope: zero-filled at startup */

int main(void)
{
    static int s_table[4];           /* static storage: also zero-filled   */
    int volts[5]    = {33, 50, 12, 18, 5};
    int inferred[]  = {10, 20, 30, 40, 50, 60};
    int partial[6]  = {7, 3};
    int zeros[8]    = {0};
    int sparse[6]   = {[1] = 11, [4] = 44};
    int i;

    printf("global   :");
    for (i = 0; i < 4; i++) printf(" %d", g_table[i]);
    printf("\nstatic   :");
    for (i = 0; i < 4; i++) printf(" %d", s_table[i]);
    printf("\nvolts    :");
    for (i = 0; i < 5; i++) printf(" %d", volts[i]);
    printf("\ninferred : %zu elements\n", sizeof inferred / sizeof inferred[0]);
    printf("partial  :");
    for (i = 0; i < 6; i++) printf(" %d", partial[i]);
    printf("\nzeros    :");
    for (i = 0; i < 8; i++) printf(" %d", zeros[i]);
    printf("\nsparse   :");
    for (i = 0; i < 6; i++) printf(" %d", sparse[i]);
    printf("\n");
    return 0;
}

Build it and run it. Notice that global and static are zero without any initializer, and that the sparse array has only two non-zero entries.

$ gcc -std=c17 -Wall -Wextra -o ep_arr_init ep_arr_init.c
$ ./ep_arr_init
global   : 0 0 0 0
static   : 0 0 0 0
volts    : 33 50 12 18 5
inferred : 6 elements
partial  : 7 3 0 0 0 0
zeros    : 0 0 0 0 0 0 0 0
sparse   : 0 11 0 0 44 0

What Happens With Too Many Initializers?

If the list is longer than the declared size, for example int a[5] = {1, 2, 3, 4, 5, 6, 7, 8};, the C standard treats it as a constraint violation. Compilers are required to print a diagnostic. GCC and Clang usually print a warning (excess elements in array initializer) and carry on, discarding the extra values, so a build with warnings turned off can ship the bug. Always compile with -Wall -Wextra and, in a real project, -Werror.

Why You Cannot Assign One C Array to Another

A beginner’s first instinct is to copy an array with b = a;. The compiler refuses. An array name is not a variable you can overwrite as a whole; in most expressions it turns into the address of its first element, and an address is not something you assign into. You must copy the elements. There are two correct ways: a for loop, or memcpy() from <string.h> with the byte count written as sizeof of the source.

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

int main(void)
{
    int src[5] = {3, 6, 9, 12, 15};
    int by_loop[5];
    int by_memcpy[5];
    int i;

    /* by_loop = src;      <-- compile error: an array is not assignable */

    for (i = 0; i < 5; i++)
        by_loop[i] = src[i];

    memcpy(by_memcpy, src, sizeof src);

    src[0] = 99;                 /* change the original afterwards */

    printf("src       :");
    for (i = 0; i < 5; i++) printf(" %d", src[i]);
    printf("\nby_loop   :");
    for (i = 0; i < 5; i++) printf(" %d", by_loop[i]);
    printf("\nby_memcpy :");
    for (i = 0; i < 5; i++) printf(" %d", by_memcpy[i]);
    printf("\n");
    return 0;
}
$ gcc -std=c17 -Wall -Wextra -o ep_arr_copy ep_arr_copy.c
$ ./ep_arr_copy
src       : 99 6 9 12 15
by_loop   : 3 6 9 12 15
by_memcpy : 3 6 9 12 15

The output proves that the two copies are independent: changing src[0] to 99 afterwards did not touch by_loop or by_memcpy. Interesting side note for later lectures: an array wrapped inside a struct can be assigned as a whole, because the struct is the object being copied.

Copying element by element

src3691215
for loopcopy i = 0 to 4one element per pass
by_loop3691215

Real-World Use Cases in Embedded C Programming

Here is where you will initialize array in C in real firmware projects.

  • Lookup tables. A sine table, a CRC table or a pin map written as static const arrays. On most MCU toolchains const data stays in flash and uses no RAM.
  • Zeroed buffers. A static receive buffer for a UART driver starts empty without any code, which is exactly what a ring buffer wants.
  • Default configuration. A partial initializer such as {115200} sets one value and leaves the rest of a settings array at a safe zero.
  • Sparse tables. Interrupt-to-handler maps where only a few slots are used, written with designated initializers so the intent is readable.

Common Mistakes When You Initialize Array in C

MistakeWhat goes wrongFix
Reading a local array before writing itRandom values, results change between runsInitialize with = {0} or fill it in a loop
Writing b = a; for arraysCompile error: array type is not assignableUse a loop or memcpy()
Counting initializers wronglySilent truncation, only a warningLeave the size empty and use sizeof to get the length
Assuming {5} fills all slots with 5Only the first element is 5, the rest are 0Loop to fill, or list every value
Huge local array on a small stackStack overflow, hard faultMake it static or file scope

Best Practices to Initialize Array in C Safely

  • Initialize every automatic array at the declaration, even when you plan to fill it soon after. It costs a few cycles and removes a whole bug class.
  • Prefer sizeof arr / sizeof arr[0] over a typed-in number so the loop bound follows the declaration.
  • Mark read-only tables const so they stay in flash and a stray write is caught at compile time.
  • Performance: = {0} on a large local array makes the compiler emit a loop or memset on every call. Use static for big scratch buffers.
  • Security: leftover stack contents can leak secrets such as old keys or passwords. Zero sensitive buffers explicitly, and never send an uninitialized array over a network.

Summary and Key Takeaways

  • Local arrays hold garbage. Static and file-scope arrays are zero.
  • An initializer list assigns values in order; missing values become zero.
  • Empty brackets let the compiler count the elements, and sizeof recovers the count.
  • {0} is the standard zero-fill idiom; designated initializers set chosen slots.
  • Too many initializers is a diagnosable error; arrays cannot be assigned with =.
  • To initialize array in C safely, choose the form that matches how the data will be used.

Conclusion

You now know what an array contains the instant it is created, and four reliable ways to give it the contents you want. These rules to initialize array in C are the foundation of safe embedded C programming: every driver buffer and lookup table depends on it. In the next lectures of this free C tutorial we use these arrays to find the largest and smallest sample, reverse data, convert numbers to binary and search a table.

Topics Covered in This Free Embedded C Lecture

free c programming coursefree c tutorialc programming for embedded systemsembedded c programmingfree embedded c coursec arrays for beginnersinitialize array in Carray initializationdesignated initializers

Frequently Asked Questions

Why does a local array contain garbage values?

A local array is placed on the stack and C does not clear it for speed. The slots hold whatever earlier function calls left behind, so you must write them before reading.

Does int a[10] = {0}; set every element to zero?

Yes. The first element gets 0 explicitly and every element without an initializer is set to zero, so the whole array is zeroed.

What if I give fewer initializers than the array size?

The given values fill the first slots in order and the rest become zero. This is true for local arrays too.

Can I leave the array size empty?

Yes, when you provide an initializer list. The compiler counts the values and sizes the array to match, which is ideal for lookup tables.

Why can I not copy one array to another with the = operator?

An array is not an assignable object in C. Copy the elements with a loop or with memcpy() and the size of the source in bytes.

Are static arrays really zero on a microcontroller without an OS?

Yes. The startup code that runs before main() clears the .bss section, so file-scope and static arrays start at zero on bare metal as well.

Keep Going With the Free Embedded C Course

Next up: finding the maximum and minimum value in an array. Practise the programs from this lecture, change the numbers and predict the output before you run them.

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *