Saturday, April 19, 2025

C++ Looping through Array using Pointers

We can use for loop in combination with pointers to get real values from arrays.

First we will create integer array with three elements:

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

Then NULL pointer is created:

int *ptrMyArr = NULL;

Then we connect a pointer and array:

ptrMyArr = myArr;

We have for loop extracting individual elements using pointers.

for (int x = 0; x < 3; x = x + 1) {
        cout << "Address ATM: " << ptrMyArr << endl;
        cout << "Value ATM: " << *ptrMyArr << endl;

        ptrMyArr = ptrMyArr + 1;
    }

Please note, because we use pointers we must jump from one memory address to another using this line in for loop:

ptrMyArr = ptrMyArr + 1;

Full script: 

#include <iostream>

using namespace std;

int main() {

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

    ptrMyArr = myArr;

    for (int x = 0; x < 3; x = x + 1) {
        cout << "Address ATM: " << ptrMyArr << endl;
        cout << "Value ATM: " << *ptrMyArr << endl;

        ptrMyArr = ptrMyArr + 1;
    }

    return 0;

}

Result:

Address ATM: 0x6dfedc
Value ATM: 55
Address ATM: 0x6dfee0
Value ATM: 66
Address ATM: 0x6dfee4
Value ATM: 77

Process returned 0 (0x0)   execution time : 0.065 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 .  ...