#include<iostream>
using namespace std;
struct data {
int x;
data *ptr;
};
int main() {
int i = 0;
while( i >=3 ) {
data *pointer = new data; // pointer points to the address of data
pointer->ptr = pointer; // ptr contains the address of pointer
i++;
}
system("pause");
}
Let us assume after iterating 3 times :
ptr had address = 100 after first loop
ptr had address = 200 after second loop
ptr had address = 300 after third loop
Now the questions are :
- Do all the three addresses that were being assigned to ptr exist in the memory after the program gets out of the loop ?
- If yes , what is the method to access these addresses after i get out of the loop ?
For starters, there will be no memory allocated for any ptr with the code you have.
This will not enter the
whileloop at all.However, if you are looking to access the ptr contained inside the
structthen you can try this. I am not sure what you are trying to achieve by assigning the ptr with its own struct object address. The program below will print the value ofxand the address assigned toptr.OUTPUT:
Personally, when I know the number of iterations I want to do, I choose
forloops and I usewhileonly when I am looking to iterate unknown number of times before a logical expression is satisfied.