PROJECTENGRAM

INITIALIZATION

Initialization

Tags: #◇CCPROG2 #◇C Programming #◇Programming #◇Computer Science #◇Data Structures #◇Data Types #◇Structured Programming #◇Memory Management


◇Overview

Array initialization assigns values to array elements at the time of declaration.

◇Key Concepts

Initializer list syntax: {val1, val2, ...} Partial initialization fills remaining elements with 0 Size can be omitted if initializer is provided Uninitialized local arrays contain garbage values

◇Details / Theory

Full Initialization

『』
C
int arr[5] = {10, 20, 30, 40, 50};  // All 5 elements set

Partial Initialization

『』
C
int arr[5] = {1, 2};  // arr = {1, 2, 0, 0, 0}

Remaining elements are automatically initialized to 0 (for numeric types) or '\0' (for char).

Size Omission

『』
C
int arr[] = {10, 20, 30};  // Compiler infers size = 3
char str[] = "Hello";       // Size = 6 (includes '\0')

Zero Initialization

『』
C
int arr[100] = {0};  // All 100 elements set to 0

String Initialization

『』
C
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
char greeting[] = "Hello";  // Equivalent, compiler adds '\0'

2D Array Initialization

『』
C
int matrix[2][3] = {
    {1, 2, 3},
    {4, 5, 6}
};

◇Common Pitfalls

Assuming uninitialized local arrays are zeroed — they contain garbage values. Forgetting the null terminator when initializing char arrays as strings. Providing more initializers than the array size — compilation error.

◇Summary

TL;DR — Arrays can be initialized at declaration using {...}. Partial initialization zeros remaining elements. Uninitialized local arrays contain garbage. String arrays need '\0' termination.

Related: ◇Declaration — ◇Accessing Elements — ◇Size — ◇Element Type — ◇One-Dimensional Arrays (1D Arrays) Source / Reference:

◇References & Navigation

CONFIRMATION // 理解度の確認

ACTIVE RECALL VERIFICATION

Select an answer to verify conceptual comprehension and reveal the technical rationale.

Q1

How do you fully initialize an array at the time of declaration?

Q2

What happens if you provide fewer initialization values than the array's size (e.g., int arr[5] = {1, 2};)?

Q3

Can you omit the size in the square brackets when initializing an array?