Jun 25, 2013 at 11:16pm
Pointers appear to point to the same address yet de-reference differnt values. I don't understand why?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
#include <iostream>
using namespace std;
void printNTimes(string *msg, int n);
int main()
{
string c = "string_c";
string d = "string_d";
string e = "string_e";
string f = "string_f";
string *mpoint = &c;
string *npoint = &d;
string *opoint = &e;
string *ppoint = &f;
printNTimes(mpoint, 5);
printNTimes(npoint, 5);
printNTimes(opoint, 5);
printNTimes(ppoint, 5);
return 0;
}
void printNTimes(string *msg, int n)
{
for( int i = 0; i < n; ++i){
cout << *msg;
cout << " :asterisk";
cout << "\t";
cout << &msg;
cout << " :ampersand: ";
cout << "\t";
cout << msg;
cout << " :nothing: ";
cout << "\n";
}
}
|
Last edited on Jun 25, 2013 at 11:46pm
Jun 25, 2013 at 11:22pm
Why did you decide that they point to the same address?
Jun 25, 2013 at 11:36pm
Well, I'm a newb, so my rational is probably flawed and I'm trying to figure out what I am missing.
The output of the function for each call shows 0x7fff2cb48348 for &msg.
I'm assuming that each pointer points to that address?
Jun 25, 2013 at 11:46pm
It is the address of the local parameter of the function. It is always the same because it points to the same variable msg.
Last edited on Jun 25, 2013 at 11:46pm
Jun 25, 2013 at 11:47pm
msg is already a pointer. It's the address of a string. To display the value of it, you simply need:
cout << msg;
&msg is the address of msg; i.e. it's the address of the argument itself. It's not the address of a string. It's the address of a pointer to a string.
Last edited on Jun 25, 2013 at 11:47pm
Jun 26, 2013 at 12:06am
Ah, makes sense now. Thank you guys much.