mehdi
mehdi

Reputation: 686

why does output of an address of pointer is different?

i am confused concerning out of an program consider we have a class like below:

#ifndef SOMECLASS
#define SOMECLASS
class SomeClass
{
    public:
        SomeClass();
        SomeClass(int);
        ~SomeClass();
        void foo(const int&);
}
#endif

and its implementation....

so in main function:

int main(int argc, char **argv){
    SomeClass* smc=new SomeClass();
    cout<<smc<<"--"<<&smc<<"--"<<&*smc; 
}

and my output a thing like below:

0xf66210----0x7ffd622a34f0----0xf66210

why does it difference among smc and &smc and &*smc? note that smc and &*smc are equal.

i am using ubuntu(14.04_x64) and+cmake(2.18)+gcc(4.8.4)

Upvotes: 1

Views: 117

Answers (4)

Ziezi
Ziezi

Reputation: 6467

To summarize the above, it can be said that:

  • smc shows the address stored in the pointer (the address of the dynamically allocated (heap) memory using new)

  • &smc shows the address of the pointer itself

  • *smc shows the content of the address (access to the members of the object - of class SomeClass)

  • &*smc points to same address as smc("alias" of the pointer, i.e. same as smc )

Upvotes: 1

Giorgi Moniava
Giorgi Moniava

Reputation: 28685

A little bit more explanation. So basically smc is a variable right? (a pointer, but a variable still). So &smc gives you the address of this variable.

Now, if you try to print value of just smc what should you get? value of the variable right? Since this is a pointer, in this case the value of this variable is address of another object to which it points.

Similarly &*smc - dereferences the pointer and gives you back address of the object dereferenced, which is similar as above value.

Upvotes: 1

Allanqunzi
Allanqunzi

Reputation: 3260

smc is the value of the pointer smc, which is the address of what smc is pointing to.

&smc is the address of the pointer smc itself.

&*smc is the address of what smc is pointing to (the being pointed to is *smc), so it is the same as smc.

Upvotes: 7

David Haim
David Haim

Reputation: 26526

there are two variables here :
1. the pointer, which is stack allocated
2. the object, which is heap allocated

smc is the address of the actual object, which exists on the heap.
consequently, &*smc dereferences the address, then references it again, yealding the same result. remember , * and & are like opposite operators, like plus and minus. adding and subtracing the same amount yealds the same result, just like dereferencing and referencing again.

&smc is the address of the pointer variable, which sits on the stack.

if it's still not clear to you, think about the following example:

int* x = nullptr;

what is x value? and what is &x?

and now?
x = new int(6)
what is the new value of x? and what is it's address?

Upvotes: 5

Related Questions