Declare and Initialize arrays in C/C++

Google Translate Icon

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:

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.

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.

 
In C, we can use malloc() and free() functions in place of new and delete operator, respectively.

2. Initialize Arrays in C/C++

a. To initialize an array in C/C++, we can provide an initializer list like,

or

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,

 
c. The array will be initialized to 0 if we provide the empty initializer list or just specify 0 in the initializer list.

 
d. If the calloc() function is used, it will allocate and initialize the array with 0.

 
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++

Rate this post

Average rating 4.43/5. Vote count: 7

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Tell us how we can improve this post?




Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and help us grow. Happy coding :)



Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Do NOT follow this link or you will be banned from the site!