Declaring and initializing arrays

Home / C Programming / Declaring and initializing arrays

Declaring and initializing arrays


C programming, you can declare and initialize arrays in different ways, depending on your requirements. Here are some common ways to declare and initialize arrays:

1. Initialize with individual values:

   int numbers[5] = {10, 20, 30, 40, 50};

   This initializes an integer array named `numbers` with 5 elements, each containing the specified values.

2. Initialize partially and let the rest be zero:

   int numbers[5] = {10, 20};

   In this case, the first two elements of the array `numbers` will be initialized with the specified values, and the remaining elements will be automatically set to zero.


3. Initialize using an initializer list:

   int numbers[] = {10, 20, 30, 40, 50};

   When the size of the array is omitted, the compiler determines the size based on the number of elements in the initializer list.

4. Initialize with a loop:

   int numbers[5];

   for (int i = 0; i < 5; i++) {

       numbers[i] = i * 10;

   }

   This method initializes the array `numbers` by assigning values to each element using a loop.

5. Initialize with a specific value:

   int numbers[5] = {0};  // All elements set to 0

   char name[10] = {'\0'};  // All elements set to null character

   In these examples, all the elements of the array are initialized to the specified value. The remaining elements will be set to the default value for that data type (0 for numbers and '\0' for characters).

6. String initialization:

   char greeting[] = "Hello, world!";

   In this case, the array `greeting` is automatically sized to accommodate the length of the provided string literal.