Saturday, April 19, 2025

C++ Array of Pointers

For every element in array, we can have an individual pointer.

Just as in last example where we listed elements and pointers, for loop will be used here.

First array of integers is created:

int myArr[3] = {55, 66, 77};

Then we state a need for Array of Pointers that will hold three memory addresses:

int *arrPtr[3];

Finally a for loop is used to list all of them:

 for (int x = 0; x < 3; x = x + 1) {
        arrPtr[x] = &myArr[x];
        cout << "Address: " << arrPtr[x] << endl;
        cout << "Value: " << *arrPtr[x] << endl;
    }

Please note that with this line we are aligning an individual pointer to individual value from our original array: 

arrPtr[x] = &myArr[x];

Full source: 

#include <iostream>

using namespace std;

int main() {

    int myArr[3] = {55, 66, 77};
    int *arrPtr[3];

    for (int x = 0; x < 3; x = x + 1) {
        arrPtr[x] = &myArr[x];
        cout << "Address: " << arrPtr[x] << endl;
        cout << "Value: " << *arrPtr[x] << endl;
    }

    return 0;

}

Result:

Address: 0x6dfee0
Value: 55
Address: 0x6dfee4
Value: 66
Address: 0x6dfee8
Value: 77

Process returned 0 (0x0)   execution time : 0.056 s
Press any key to continue.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...