Array of pointers in C ++

Before we understand the concept of pointer arrays, we consider the following example, which uses an array of 3 integer numbers.

Before we understand the concept of pointer arrays, we consider the following example, which uses an array of 3 integer numbers:

 #include using namespace std ; const int MAX = 3 ; int main () { int var [ MAX ] = { 10 , 100 , 200 }; for ( int i = 0 ; i < MAX ; i ++) { cout << "Gia tri cua var[" << i << "] = " ; cout << var [ i ] << endl ; } return 0 ; } 

When the above code is compiled and executed, it gives the following result:

 Gia tri cua var [ 0 ] = 10 Gia tri cua var [ 1 ] = 100 Gia tri cua var [ 2 ] = 200 

There is a situation when we want to maintain an array, which can store pointers to an int or char data type or any other type. Following is the declaration of an array of pointers to an integer:

 int * contro [ MAX ]; 

It declares the contro as an array of MAX pointer integers. Therefore, each element in contro, now holds a pointer to an int value. The following example uses 3 integer numbers, which will be stored in an array of pointers as follows:

 #include using namespace std ; const int MAX = 3 ; int main () { int var [ MAX ] = { 10 , 100 , 200 }; int * contro [ MAX ]; for ( int i = 0 ; i < MAX ; i ++) { contro [ i ] = & var [ i ]; // gan dia chi cua so nguyen. } for ( int i = 0 ; i < MAX ; i ++) { cout << "Gia tri cua var[" << i << "] = " ; cout << * contro [ i ] << endl ; } return 0 ; } 

When the above code is compiled and executed, it gives the following result:

 Gia tri cua var [ 0 ] = 10 Gia tri cua var [ 1 ] = 100 Gia tri cua var [ 2 ] = 200 

You can use an array of pointers to characters to store a list of strings as follows:

 #include using namespace std ; const int MAX = 4 ; int main () { char * tensv [ MAX ] = { "Nguyen Thanh Tung" , "Tran Minh Chinh" , "Ho Ngoc Ha" , "Hoang Minh Hang" , }; for ( int i = 0 ; i < MAX ; i ++) { cout << "Gia tri cua tensv[" << i << "] = " ; cout << tensv [ i ] << endl ; } return 0 ; } 

Running the above C ++ program will produce the following results:

Picture 1 of Array of pointers in C ++

According to Tutorialspoint

Previous article: Cursor and Array in C ++

Next article: Pointers to pointers in C ++

Update 25 May 2019
Category

System

Mac OS X

Hardware

Game

Tech info

Technology

Science

Life

Application

Electric

Program

Mobile