Four ways to initialize arrays in the C language.
There are four ways to initialize arrays in the C language.
- Static initialization: assigning initial values directly when declaring an array. For example:
int arr[] = {1, 2, 3, 4, 5};
This method is suitable for situations where the size of the array is known in advance.
- Dynamic initialization: First declare the array, then use a loop structure to assign values to the array elements. For example:
int arr[5];
for (int i = 0; i < 5; i++) {
arr[i] = i + 1;
}
This method is suitable for situations where the size of the array is not known beforehand and needs to be determined based on runtime conditions.
- Partial initialization: assigning initial values to only certain elements of an array, with the remaining elements automatically initialized to 0. For example:
int arr[5] = {1, 2};
This method is suitable for cases where only some elements of the array are of concern, and it is not necessary to assign initial values to all elements.
- String initialization: Initialize character array using string constants. For example:
char str[] = "Hello";
This method is suitable for cases where initializing a character array as a string is needed.
It is important to note that when initializing an array, if the size is not explicitly specified, the compiler will automatically calculate the size based on the number of elements being initialized.