Pointers to Structs

Trying to figure out why the addresses of &aStruct and ptr are different from the value of &strr in the function ListStruct:


#include "stdafx.h"
#include <string>
#include <iostream>

using namespace std;


struct jTest {
string first;
string second;
string third;
};

void ListStruct(jTest *strr);

int _tmain(int argc, _TCHAR* argv[])
{
jTest aStruct = { "omr", "two", "three"};
jTest * ptr;
ptr = &aStruct;

//Checks on value of &aStruct and ptr;
cout << "The value of &aStruct is " << &aStruct << " and the value of ptr is " << ptr << endl;

ListStruct(ptr);

cin.get();
}

void ListStruct(jTest *strr) {
cout << "The address of &strr is " << &strr << endl;
}

Returns:
The value of &aStruct is 0026F6CC and the value of ptr is 0026F6CC
The address for &strr is 0026F5E8

Why the difference in addresses?

BTW the difference is always 228 bytes.

Thanks,
John
void ListStruct(jTest *strr) {
cout << "The address of &strr is " << &strr << endl;
}


I believe sttr is storing the contents of ptr in the main program. If you do a cout << *strr << "\n" you should see back 0026F6CC.

Changed it and this came back:


Error 1 error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'jTest' (or there is no acceptable conversion) c:\users\bridget\documents\visual studio 2010\projects\structsand ptrs\structsand ptrs\structsand ptrs.cpp 34


Thanks,
John
closed account (D80DSL3A)
Try cout << "The address pointed to by strr is " << strr << endl;. This should agree with the value of ptr.

&strr would be the address where the pointer strr is stored - not the value (strr) contained there.
Note: &strr won't = &ptr since strr is a local copy of ptr. They are 2 distinct pointers but the same value is stored in them.
Thank you fun2code. Your explanation makes perfect sense. The value stored in ptr being the address of where the struct lives. Now I have to play with it some more to get it right in my mind. Thanks again for your help.

Topic archived. No new replies allowed.