Reputation: 291
I just made a tiny stupid program about passing a variable the value contained in another using a pointer, just as an introduction to pointers themselves. I printed, before and after the assignation, the value and position of all three variables involved. However, I get, as the value contained inside the pointer, an address different from the variable it is pointing to's one, and I just can't understand why.
This is my main program:
#include <iostream>
#include "01.Point.h"
using namespace std;
int main()
{
int a,b;
cout << "Insert variable's value: ";
cin >> a;
int * point;
cout << "Before assignment:" << endl;
printeverything (a,b,point);
point = &a;
b = * point;
cout << "After assignment:" << endl;
printeverything (a,b,point);
cout << endl;
}
And this is my function's implementation:
#include <iostream>
#include "01.Point.h"
using namespace std;
void printeverything (int a, int b, int * c) {
cout << "First variable's value: " << a << "; its address: " << &a << endl;
cout << "Second variable's value: " << b << "; its address: " << &b << endl;
cout << "Pointer's value: " << c << "; its address: " << &c << endl;
}
b successfully gets a's value, so everything works right, but this is the complete output:
Before assignment:
First variable's value: 5; its address: 0x7fffee49b77c
Second variable's value: 0; its address: 0x7fffee49b778
Pointer's value: 0x7fffee49b8a0; its address: 0x7fffee49b770
After assignment:
First variable's value: 5; its address: 0x7fffee49b77c
Second variable's value: 5; its address: 0x7fffee49b778
Pointer's value: 0x7fffee49b7ac; its address: 0x7fffee49b770
I mean, if variable x is at position 3285, and i do p = &x
, pointer p should contain value 3285, right? So why is this happening?
Upvotes: 1
Views: 748
Reputation: 28000
In your printeverything
function, the parameter/local variable a
is an entirely different variable from the one you passed to it. It happens to have the same name, but that's (as far as the compiler is concerned) entirely a coincidence - it's a different variable with a different address; you can see this by assigning a value to a
within the function, and then printing it afterwards - you'll see that the "outer" a
will remain unchanged.
Upvotes: 6