Array Initialization In C





Array initialization in C refers to the process of assigning initial values to the elements of an array when it is declared. This means that when an array is created, specific values can be given to its elements right from the beginning, instead of assigning them later individually.

There are two main ways to initialize an array:

  1. At the time of declaration (static initialization).
  2. Element-by-element assignment after declaration (dynamic initialization).


Array declaration and Initialization example

Array Declaration and Initialization
Type of Array Initialization Link
Integer Array
int intArray[5] = {1, 2, 3, 4, 5};
Learn More
Character Array
char charArray[5] = {'a', 'b', 'c', 'd', 'e'};
Learn More
Float Array
float floatArray[5] = {1.1, 2.2, 3.3, 4.4, 5.5};
Learn More
Double Array
double doubleArray[5] = {1.111, 2.222, 3.333, 4.444, 5.555};
Learn More
Long Array
long longArray[5] 
= {1000000000, 2000000000, 3000000000, 4000000000, 5000000000};
Learn More
Short Array
short shortArray[5] = {1, 2, 3, 4, 5};
Learn More
Unsigned Integer Array
unsigned int unsignedIntArray[5] = {1, 2, 3, 4, 5};
Learn More
Unsigned Long Array
unsigned long unsignedLongArray[5] 
= {1000000000, 2000000000, 3000000000, 4000000000, 5000000000};
Learn More
Unsigned Short Array
unsigned short unsignedShortArray[5] = {1, 2, 3, 4, 5};
Learn More
Boolean Array (Using int)
int boolArray[2] = {1, 0}; // true, false
Learn More


Different Type of Declaration and initialization of array in c

In C programming, you can declare and initialize an array in various ways. Here are some common methods:


  1. Static Initialization: Declare and initialize the array with predefined values at the time of declaration.
        int arr1[5] = {1, 2, 3, 4, 5};
        
  2. Dynamic Initialization: If you're initializing the array dynamically, you can use a loop or other logic to assign values.
        int arr2[5];
        for (int i = 0; i < 5; i++) {
        arr2[i] = i + 1;
        }
        
  3. Partial Initialization: You can partially initialize an array, and the remaining elements will be automatically initialized to 0.
        int arr3[5] = {1, 2}; // arr3[0] = 1, arr3[1] = 2, arr3[2] = 0, arr3[3] = 0, arr3[4] = 0
        
  4. Designated Initializers (C99 and later): You can specify which elements of the array you want to initialize.
        int arr4[5] = {[0] = 1, [2] = 3}; // arr4[0] = 1, arr4[1] = 0, arr4[2] = 3, arr4[3] = 0, arr4[4] = 0
        
  5. String Initialization: Arrays can be initialized with strings. Strings in C are arrays of characters.
        char str[] = "Hello"; // str[0] = 'H', str[1] = 'e', ..., str[4] = 'o', str[5] = '\0'