Array Declaration and Initialization

Arrays in C are sequences of items of the same type, such as integers. When declaring an array, you specify its size. For example, int myArray[4]; creates an array of four integers. The array name (myArray) is a pointer to the first element and cannot be changed. Starting with C99, arrays can be declared with non-constant sizes using a previously initialized variable, e.g., int myArray[x];. To enable C99 features, use the compiler option --std=gnu99.

An array can be initialized at the time of declaration using curly braces. For instance, int myArray[4] = {42, 39, 16, 7}; initializes the array with these values. If fewer elements are provided, the remaining elements are zero-initialized. For example, int myArray[4] = {0}; initializes all elements to zero.

Additionally, if an initializer is provided, the array size can be omitted, and the compiler will determine the size based on the number of elements in the initializer: int myArray[] = {42, 39, 16, 7};.

Structs can also be initialized similarly. For example, point p = {3, 4}; initializes the fields of the struct. C99 allows designated initializers to specify which fields to initialize, making the code more robust: point p = { .x = 3, .y = 4};. This can be combined to initialize arrays of structs:

point myPoints[] = { {.x = 3, .y = 4}, {.x = 5, .y = 7}, {.x = 9, .y = 2} };

Key Points

point myPoints[] = { {.x = 3, .y = 4}, {.x = 5, .y = 7}, {.x = 9, .y = 2} };

Example Table

Concept Example Code Description
Array Declaration int myArray[4]; Declares an array of 4 integers.
Array Initialization int myArray[4] = {42, 39, 16, 7}; Initializes array with specified values.
Zero Initialization int myArray[4] = {0}; Initializes all elements to zero.
Non-constant Size int myArray[x]; (with --std=gnu99) Declares array with size determined by variable x.
Omitted Size int myArray[] = {42, 39, 16, 7}; Compiler determines array size from initializer.
Struct Initialization point p = { .x = 3, .y = 4}; Initializes struct fields with designated initializers.
Array of Structs point myPoints[] = { {.x = 3, .y = 4}, {.x = 5, .y = 7}, {.x = 9, .y = 2} }; Initializes array of structs.