![]() |
VOOZH | about |
An array in any programming language is a collection of similar data items stored at contiguous memory locations and elements can be accessed randomly using array indices. It can be used to store the collection of primitive data types such as int, float, double, char, etc of any particular type. For example, an array in C/C++ can store derived data types such as structures, pointers, etc. Below is the representation of an array.
The arrays can be declared and initialized globally as well as locally(i.e., in the particular scope of the program) in the program. Below are examples to understand this concept better.
Program 1: Below is the C++ program where a 1D array of size 107 is declared locally.
Output:
Explanation: In the above program, a segmentation fault error occurs when a 1-D array is declared locally, then the limit of that array size is the order of 105. It is not possible to declare the size of the array as more than 105. In this example, the array of size 107 is declared, hence an error has occurred.
Program 2: Below is the program where a 1-D array of size 105 is initialized:
1
Explanation: In the above program, the code compilation is successful, and the output is 1. This is because the 1D array of size 105 is initialized locally and this is valid.
Program 3: Below is the program where a 1-D array of size 107 is declared globally.
1
Explanation: In the above code compilation is successful, and the output is 1. This is because a 1-D array of size 107 is declared globally and this is valid.
Note: If a 1-D array of size 108 is declared globally, then again the segmentation fault error will be encountered because there is also a limit for global declaration of the 1-D array and that is, it is possible to only declare a 1-D array globally up to 107 sizes.
Why global array has a larger size than the local array?