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:
According to Tutorialspoint
Previous article: Cursor and Array in C ++
Next article: Pointers to pointers in C ++
You should read it
Maybe you are interested
Sending employees to supermarket sales, Australian Airlines has created jobs for 5,000 people who are unemployed because they stopped flying Bloomberg: The Covid-19 epidemic could cause most airlines to go bankrupt until May Six versions of Half-Life and Half-Life 2 are being played for free, please experience 4 websites to book super cheap air tickets, helping people who often fly 'saving' air tickets 4 simple steps to clean the shower 13 great uses of PAPER you may not know