Table of Contents
Array of Pointers in C ++ is easier to understand when the core ideas are paired with practical examples. The sections below explain the topic clearly, highlight useful steps, and point out details that can prevent common errors.
Before we understand the concept of pointer arrays, we consider the example below, 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 ; }
Frequently Asked Questions
What is Array of Pointers in C ++?
Array of Pointers in C ++ refers to the core ideas, tools, or processes explained in this guide. Understanding the basics makes the more advanced details easier to apply.
Why is Array of Pointers in C ++ important?
A clear understanding of Array of Pointers in C ++ helps you make informed decisions, avoid common mistakes, and use the relevant tools or techniques more effectively.
How should beginners approach Array of Pointers in C ++?
Start with the fundamental concepts, follow the examples step by step, and test each change in a safe environment before applying it to important systems or data.
Was this article helpful?
Your feedback helps us improve.
Reader Comments 0
Sign in with email or Google to join the discussion.