+ 1

This question is related to pointers and objects. I have commented out my issue.

#include<iostream> #include<conio.h> using namespace std; class item { int code; float price; public: void getData(int a, float b) { code=a; price=b; } void show(void) { cout<<"Code: "<<code<<"\n"; cout<<"price: "<<price<<"\n"; } }; const int size=2; int main() { item *p=new item[size]; //defining an array of objects or pointers to objects; item *d=p; //what does this mean? int x, i; float y; for(int i=0; i<size; i++) { cout<<"Input code and price for item "<<i+1; cin>>x>>y; p->getData(x,y); p++; } for(int i=0; i<size; i++) { cout<<"Item: "<<i+1<<"\n"; d->show(); //I tried swapping d with p, thinking they must represent same address d++; //but it gave improper output. I am obliged to use d++ } return 0; }

10th Jun 2020, 11:15 PM
Prashant Pant
Prashant Pant - avatar
3 Answers
+ 3
*d = p is a pointer alias where d refers to the same memory address as pointer p (as I think you already knew). But in the first for-loop you offset the pointer 'p' two times so now 'd' and 'p' no longer point to the same memory address. 'p' points to a region of memory past the end and 'd' points to the base address of the array. If you subtract the offset from p (p -= size) after the first loop, then 'p' will point to the base address like pointer 'd' and you can use either of them in the second loop. You will need at least one pointer to the base address so you can call delete[] on the array you allocated.
11th Jun 2020, 12:17 AM
Gen2oo
Gen2oo - avatar
+ 2
Both *p and *d are pointing to the first item location. After initializing the items(using input) your p pointer is not pointing to the first item anymore(but d is). That's why d is used. See↓ This works: https://code.sololearn.com/cMc12QKd8FbU/?ref=app I am a c++ noob but I think this version is better: https://code.sololearn.com/c6191xaZsvsz/?ref=app
11th Jun 2020, 12:20 AM
Kevin ★
0
Why is it so?What does *d=p mean? What is it representing here?
10th Jun 2020, 11:16 PM
Prashant Pant
Prashant Pant - avatar