Posted By:
11 Jun, 2013 12:11 am PDT

Arrays in C and C++

How do arrays work and give some examples.


An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Please watch the video for details..

Was it useful?  

Arrays store only similar kind of Data.

The syntax for declaring an array goes like this :

datatype arrayname[array_size].

Datatype is used to declare the type of data being stored into the array .

Arrayname is used to give a specific name to the memory space.

Size is used to allocate that particular amount of space.


Initializing Arrays

You can initialize arrays in  C as follows:

double price[5] = {1000.0, 21.0, 3.7, 76.0, 50.0};

The number in square brackets indicates the size of an array. It means that the array can hold only five elements. 


When you do not know the exact size of an array and want to initialize it dynamically, you can use the following syntax:

double price[] = {1000.0, 21.0, 3.7, 76.0, 50.0};

You can also assign values to array elements one by one:

double price[0] = 1000.0;
double price[1] = 21.0;
double price[4]=50.0;

The above statement assigns element number 5th in the array with a value of 50.0. All arrays have 0 as the index of their first element which is also called base index and last index of an array will be total size of the array minus 1. 


Array Bounds Checking

The first and last positions in an array are called its bounds. Remember that the bounds of an array are zero and the integer that equals the number of elements it contains, minus one.

Although C will not warn you at compile-time when you exceed the bounds of an array, the debugger can tell you at run-time.

Was it useful?  

Please login to reply to this problem.

Related Problems on Fixoncloud