This post will discuss how to declare and initialize arrays in C/C++.
1. Declare Arrays in C/C++
⮚ Allocate memory on Stack
In C/C++, we can create an array, as shown below:
|
1 |
int arr[5]; |
The above code creates a static integer array having size 5. It will allocate the memory on the stack, and the scope of this memory is limited to the scope of the function in which the array is declared. This memory will be freed automatically once we exit the function.
⮚ Allocate memory on Heap
In C++, we can create a dynamic array by using the new operator. With the new operator, the memory is allocated for the array at run time on the heap. For example, the following code will create a dynamic integer array having size 5 on the heap.
|
1 |
int *arr = new int[5]; |
If not enough memory is available for the array, heap overflow will happen. Please be careful to explicitly free this memory using the delete operator; otherwise, a memory leak will occur and might crash the program at some point.
|
1 |
delete[] arr; |
In C, we can use malloc() and free() functions in place of new and delete operator, respectively.
|
1 2 3 4 |
int n = 5; int *arr = (int*)malloc(n*sizeof(int)); // rest of the code free(arr); |
2. Initialize Arrays in C/C++
a. To initialize an array in C/C++, we can provide an initializer list like,
|
1 |
int arr[5] = { 1, 2, 3, 4, 5 }; |
or
|
1 |
int arr[] = { 1, 2, 3, 4, 5 }; |
The array elements will appear in the same order as elements specified in the initializer list.
b. In case we specify the size, but omit few values from the initializer list, the remaining values will be initialized to 0. For example,
|
1 |
int arr[5] = { 1, 2, 3 }; // results in [1, 2, 3, 0, 0] |
c. The array will be initialized to 0 if we provide the empty initializer list or just specify 0 in the initializer list.
|
1 2 |
int arr[5] = {}; // results in [0, 0, 0, 0, 0] int arr[5] = { 0 }; // results in [0, 0, 0, 0, 0] |
d. If the calloc() function is used, it will allocate and initialize the array with 0.
|
1 2 3 4 |
int n = 5; int *arr = (int*)calloc(n, sizeof(int)); // arr = [0, 0, 0, 0, 0] // rest of the code free(arr); |
e. Please note that the global arrays will be initialized with their default values when no initializer is specified. For instance, the integer arrays are initialized by 0. Double and float values will be initialized with 0.0. For char arrays, the default value is '\0'. For an array of pointers, the default value is nullptr. For strings, the default value is an empty string "".
That’s all about declaring and initializing arrays in C/C++.
Read More:
Initialize all elements of an array to the same value in C/C++