{{announcement.body}}
{{announcement.title}}

Arrays in C/C++

DZone 's Guide to

Arrays in C/C++

In this article, we discuss fundamentals behind arrays in C and C++, including single and multi-dimensional arrays and pointers to arrays.

· Web Dev Zone ·
Free Resource

C++ provides a data structure, the array, which stores a fixed-size, sequential collection of elements of the same type. They are used to store similar types of elements. (The data type must be the same for all elements.) They can be used to store collections of primitive data types, such as int, float, double, char, etc. of any particular type. To add to it, an array in C or C++ can store derived data types, such as structures, pointers etc.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first element, and the highest address to the last element.

If you want to follow video tutorial, check it out below:


You may also like: The Best of Java Collections [Tutorials].

Array Declaration

To declare an array in C++, the programmer specifies the type of the elements and the number of elements in the array like:

C++
 




xxxxxxxxxx
1


 
1
type Name_of_array [ arraySize ];



This is called a single-dimension array. arraySize must be an integer constant greater than zero, and type can be any valid C++ data type. For example, to declare a 5-element array of type double, use this statement:

C++
 




xxxxxxxxxx
1


 
1
double bal[5];


 

There are various ways in which we can declare an array. It can be done by specifying its type and size by initializing it or both.

  1. Array declaration by specifying size 
C++
 




xxxxxxxxxx
1


 
1
// With recent C/C++ versions, we can also
2
 
          
3
// declare an array of user specified size
4
 
          
5
int n = 10;
6
 
          
7
int arr2[n]; 



  1. Array declaration by initializing elements
C++
 




xxxxxxxxxx
1


 
1
// Array declaration by initializing elements 
2
               
3
 
          
4
int arr[] = { 10, 20, 30, 40 }              
5
 
          
6
// Compiler creates an array of size 4. 
7
 
          
8
// above is same as  "int arr[4] = {10, 20, 30, 40}" 



  1. Array declaration by specifying size and initializing elements 
C++
 




xxxxxxxxxx
1


 
1
int arr[6] = { 10, 20, 30, 40 } 
2
 
          
3
// above is same as  "int arr[] = {10, 20, 30, 40, 0, 0}" 



Advantages of an Array in C/C++:

  1. Random access of elements using array index.
  2. Use less code, as it creates a single array of multiple elements.   
  3. Easy access to all the elements.   
  4. Traversal through the array becomes easy using a single loop.  
  5. Sorting becomes easy, as it can be accomplished by writing less code.

Disadvantages of an Array in C/C++:

  1. Allows a fixed number of elements to be entered, which is decided at the time of declaration. Unlike a linked list, an array in C is not dynamic.
  2. Insertion and deletion of elements can be costly since the elements are needed to be managed in accordance with new memory allocation.

Example of arrays:

C++
 




xxxxxxxxxx
1
35


 
1
#include <iostream> 
2
 
          
3
using namespace std; 
4
 
          
5
  
6
 
          
7
int main() 
8
 
          
9
{ 
10
 
          
11
    int arr[5]; 
12
 
          
13
    arr[0] = 5; 
14
 
          
15
    arr[2] = -10; 
16
 
          
17
  
18
 
          
19
    // this is same as arr[1] = 2 
20
 
          
21
    arr[3 / 2] = 2; 
22
 
          
23
    arr[3] = arr[0]; 
24
 
          
25
  
26
 
          
27
    cout << arr[0] << " " << arr[1] 
28
 
          
29
         << " " << arr[2] << " " << arr[3]; 
30
 
          
31
  
32
 
          
33
    return 0; 
34
 
          
35
} 



Output: 

C++
 




xxxxxxxxxx
1


 
1
5 2 -10 5


   
Example of elements are stored at contiguous memory locations

C++
 




xxxxxxxxxx
1
18


 
1
#include <iostream> 
2
 
          
3
using namespace std;   
4
 
          
5
int main() 
6
{ 
7
 
          
8
    int arr[5], i; 
9
    cout << "Size of integer in this compiler is " << sizeof(int) << "\n"; 
10
 
          
11
    for (i = 0; i < 5; i++) 
12
 
          
13
        cout << "Address arr[" << i << "] is " << &arr[i] << "\n"; 
14
 
          
15
 
          
16
    return 0; 
17
 
          
18
} 



Output: 

C++
 




xxxxxxxxxx
1
11


 
1
Size of integer in this compiler is 4
2
 
          
3
Address arr[0] is 0x7ffdb4260
4
 
          
5
Address arr[1] is 0x7ffdb4264
6
 
          
7
Address arr[2] is 0x7ffdb4268
8
 
          
9
Address arr[3] is 0x7ffdb426c
10
 
          
11
Address arr[4] is 0x7ffdb4270


 

Multi-Dimensional Arrays

C++ allows multidimensional arrays. Here is the general form of a multidimensional array declaration −

C
 




xxxxxxxxxx
1


 
1
type name[size1][size2]...[sizeN];



For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array −

C
 




xxxxxxxxxx
1


 
1
int threedim[5][10][4];



Two-Dimensional Arrays

The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size x,y, you would write something as follows:

C
 




xxxxxxxxxx
1


 
1
type arrayName [ x ][ y ];



Type can be any valid C++ data type, and arrayName will be a valid C++ identifier.

A two-dimensional array can be thought of as a table, which will have x number of rows and y number of columns. A two-dimensional array a, which contains three rows and four columns can be shown as follows:

Two Dimensional Array example

Two Dimensional Array example

Every element in an array a is identified by an element name of the form a[ i ][ j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in a.

Initializing Two-Dimensional Arrays

Multi-dimensioned arrays may be initialized by specifying bracketed values for each row. The following is an array with 3 rows, where each row has 4 columns.

C++
 




xxxxxxxxxx
1


 
1
int a[3][4] = {  
2
 
          
3
   {0, 1, 2, 3} ,   /*  initializers for row indexed by 0 */
4
 
          
5
   {4, 5, 6, 7} ,   /*  initializers for row indexed by 1 */
6
 
          
7
   {8, 9, 10, 11}   /*  initializers for row indexed by 2 */
8
 
          
9
};



The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to previous example −

C
 




xxxxxxxxxx
1


 
1
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};


Accessing Two-Dimensional Array Elements

An element in a two-dimensional array is accessed by using subscripts (i.e., row index and column index of the array). For example:

C
 




xxxxxxxxxx
1


 
1
int val = a[2][3];



The above statement will take the 4th element from the 3rd row of the array. You can verify this in the above diagram.

C++
 




xxxxxxxxxx
1
28


 
1
#include <iostream>
2
 
          
3
using namespace std;
4
 
          
5
int main () {
6
 
          
7
   // an array with 5 rows and 2 columns.
8
 
          
9
   int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
10
 
          
11
   // output each array element's value                      
12
 
          
13
   for ( int i = 0; i < 5; i++ )
14
 
          
15
      for ( int j = 0; j < 2; j++ ) {
16
 
          
17
      
18
         cout << "a[" << i << "][" << j << "]: ";
19
 
          
20
         cout << a[i][j]<< endl;
21
 
          
22
      }
23
 
          
24
 
25
 
          
26
   return 0;
27
 
          
28
}



Output:

C
 




xxxxxxxxxx
1
10


 
1
a[0][0]: 0
2
a[0][1]: 0
3
a[1][0]: 1
4
a[1][1]: 2
5
a[2][0]: 2
6
a[2][1]: 4
7
a[3][0]: 3
8
a[3][1]: 6
9
a[4][0]: 4
10
a[4][1]: 8



As explained above, you can have arrays with any number of dimensions, although it is likely that most of the arrays you create will be of one or two dimensions.

Pointer to an Array

It is most likely that you would not understand this chapter until you have a decent understanding of pointers.

So, assuming you have bit understanding on pointers in C++, let us start: An array name is a constant pointer to the first element of the array. Therefore, in the declaration:

C++
 




xxxxxxxxxx
1


 
1
double balance[50];



balance is a pointer to &balance[0], which is the address of the first element of the array balance. Thus, the following program fragment assigns p the address of the first element of balance:

C++
 




xxxxxxxxxx
1


 
1
double *p;
2
 
          
3
double balance[10];
4
 
          
5
p = balance;



It is legal to use array names as constant pointers, and vice versa. Therefore, *(balance + 4) is a legitimate way of accessing the data at balance[4].

Once you store the address of first element in p, you can access array elements using *p,  *(p+1), *(p+2), and so on. Below is the example to show all the concepts discussed above:

Java
 




xxxxxxxxxx
1
40


 
1
#include <iostream>
2
 
          
3
using namespace std;
4
 
          
5
 
6
int main () {
7
 
          
8
   // an array with 5 elements.
9
 
          
10
   double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
11
 
          
12
   double *p;
13
 
          
14
   p = balance; 
15
 
          
16
   // output each array element's value 
17
 
          
18
   cout << "Array values using pointer " << endl;
19
 
          
20
   for ( int i = 0; i < 5; i++ ) {
21
 
          
22
      cout << "*(p + " << i << ") : ";
23
 
          
24
      cout << *(p + i) << endl;
25
 
          
26
   }
27
 
          
28
   cout << "Array values using balance as address " << endl;
29
 
          
30
   for ( int i = 0; i < 5; i++ ) {
31
 
          
32
      cout << "*(balance + " << i << ") : ";
33
 
          
34
      cout << *(balance + i) << endl;
35
 
          
36
   }
37
 
          
38
   return 0;
39
 
          
40
}



Output:

C++
 




xxxxxxxxxx
1
23


 
1
Array values using pointer
2
 
          
3
*(p + 0) : 1000
4
 
          
5
*(p + 1) : 2
6
 
          
7
*(p + 2) : 3.4
8
 
          
9
*(p + 3) : 17
10
 
          
11
*(p + 4) : 50
12
 
          
13
Array values using balance as address
14
 
          
15
*(balance + 0) : 1000
16
 
          
17
*(balance + 1) : 2
18
 
          
19
*(balance + 2) : 3.4
20
 
          
21
*(balance + 3) : 17
22
 
          
23
*(balance + 4) : 50



In the above example, p is a pointer to double, which means it can store an address of a variable of double type. Once we have address in p, then *p will give us value available at the address stored in p, as we have shown in the above example.


Further Reading

Topics:
array, c, c++, pointer, tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}