- #1
yungman
- 5,718
- 241
- TL;DR Summary
- I just want to verify I am correct in my understanding of this.
Hi
I am working on Chapter 11 Structure, this is pointer of structure where the structure has a member that is a pointer variable. I just want to run by you guys to make sure my understanding is correct. Below is a program I wrote for verification. It works...BUT I afraid it's like last time, it was so close and was so wrong!
I put as much comments in the program. Can you help me check my comments? I also show the output of running the program from line 40 to 46 to verify what I said.
Thanks
I am working on Chapter 11 Structure, this is pointer of structure where the structure has a member that is a pointer variable. I just want to run by you guys to make sure my understanding is correct. Below is a program I wrote for verification. It works...BUT I afraid it's like last time, it was so close and was so wrong!
C++:
//pointer to struct with pointer
#include <iostream>
using namespace std;
struct test
{
int x;//member variable x of integer
int* pt;//member pointer variable pt of integer
};
void getMember(test*);
int main()
{
int y = 20;// declare y = 20
test t = { 15, &y }; // set initial value of x=15 and pt=&y ( address of y)
test* stpt; //declare pointer stpt of test.
stpt = &t;//initialize stpt to point to t where t is test type struct pointer
cout << " address of y=&y = " << &y;// display address of variable y
getMember(&t);
return 0;
}
void getMember(test*stpt)
{
// on the same line as &y to show stpt->pt and (*stpt).pt all equal to &y which is address of y
//()has to be used because dot take precedence to indirectional operator *. (*stpt).pt means dereferencing
// pointer stpt that point to the address of pointer pt.
cout << " address of y=stpt->pt= " << stpt->pt << " =(*stpt).pt= " << (*stpt).pt << "\n\n";
// show the content of x = 15 after passing to function
cout << " content of x = " << (stpt->x) << "\n\n";
// show the content of y = 20 using *(stpt->pt) and *stpt->pt
//stpt->pt is dereference stpt to give address of pt. *stpt->pt = *(stpt->pt) is dereferencing
// the pointer pt to get the content of y = 20
cout << " content y = *(stpt->pt) = " << *(stpt->pt) << "\n\n";
cout << " content y = *stpt->pt = " << *stpt->pt << "\n\n";
}
// address of y=&y = 012FFD30 address of y=stpt->pt= 012FFD30 =(*stpt).pt= 012FFD30
//content of x = 15
//content y = *(stpt->pt) = 20
//content y = *stpt->pt = 20
I put as much comments in the program. Can you help me check my comments? I also show the output of running the program from line 40 to 46 to verify what I said.
Thanks