Array of Pointers in C++

Array of pointers in C++: This can be defined as an array is a list or holding tank for a set of values. Once those values are set it’s very hard to re-order them or add new items. So for this purpose, we can use the array of pointers. And also keep in mind that an array is a single element with multiple components.

Array of pointers in C++

A pointer holds an address to something. It’s kind of like an address because it POINTS to a specific value.

array of pointers in c++

pointer payCode pointing to a value of 507



Example:

#include<iostream>
using namespace std;
const int MAX = 3;
int main() {
   int  var[MAX] = {10, 100, 200};
   int *ptr[MAX];
   for (int i = 0; i < MAX; i++) {
      ptr[i] = &var[i]; //assign the address of integer.
   }
   for(int i = 0; i< MAX; i++) {
      cout<<"Value of var[" << i << "] = ";
      cout<< *ptr[i] << endl;
   }
   return 0;
}

Output:

Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200

Example: an array of pointers to store the list of  strings

#include<iostream>
using namespace std;
const int MAX = 4;
int main() {
const char *names[MAX] = {"Zara Ali", "Hina Ali", "Nuha Ali", "Sara Ali"}
   for (int i = 0; i < MAX; i++) {
      cout<< "Value of names[" << i << "] = ";
      cout<< (names + i) << endl;
   }
   return 0;
}

Output:

Value of names[0] = 0x7ffd256683c0
Value of names[1] = 0x7ffd256683c8
Value of names[2] = 0x7ffd256683d0
Value of names[3] = 0x7ffd256683d8