Search code examples
programming-languagesc++cpointersreference

I wonder what really the &a returns?


Suppose

First case

 int a;
 int *p= &a ; it works no error

Second case

 long int a;
 long int b;
 b = & a; it wont work 

Most of us say b is a variable not a pointer. But see the below.

So the question is if the &a returns the address which is an unsigned integer then why cant we assign it to a normal variable? But why only to pointers? See below

b = (unsigned int) &a ; it works after typecasting though its not practicable.

If the address is integer format then why don't the unsigned or long integers save it? I was thinking, there must be some hidden secret behind it. Could anyone reveal it? What I thought is, pointers must be doing something inside but I wonder what it would be and why a normal variable cant be.

Thanks for all your answers but the actual question what really the &a returns? Integer value or not? if it is integer number why a variable cannot hold it? long int a =65535 \valid why not int a= &b if value of address b is 65535

I'm not worried to use it as pointer, please the question is about just saving the value. Not deferencing the address. People saying 32 or 64 bit, I'm not worried about that. Why it cant save the address if address is a integer number?

I mean why cant we assign the value, I'm not saying to assign the properties of pointers to variable but just assign the value thats it

a=65535
b = a \\ works it assigns b - 65535
&a=65535
b = & a   \\ doesn't work, if address is a some integer value,why we can't store it in a variable?

take the 16 bit as example normal pointer (the address ) size is 2 bytes and variable size is 2 bytes why cant we store the address in other variable if address is integer value thats my question i find many answers like ++ it increments by 4 to pointer and value 1 to variable, not worried about that just assigning the value is more important question.

  b = & a ; address of a is 4000
  ++b ; becomes 4001 thats it,thats not a problem 

Solution

  • Integers, even long int, are not always going to be the same size as a pointer. Sometimes they will be (for example, most 32-bit architectures have sizeof(int) == sizeof(void *)), sometimes they will be different (for example, some 64-bit architectures have sizeof(long) == sizeof(void *) but some do not -- Visual C++ on Windows being a prime example of a compiler where sizeof(long) != sizeof(void *)).

    There's also the fact that void * is simply not the same type as long int.

    Imagine a class Foo and a class Bar, defined like so:

    class Foo {
       public: int a;
    };
    
    class Bar {
       public: int b;
    };
    

    It's like asking why you can't assign an instance of class Foo to a variable of type Bar -- they're not the same thing, even though in this case both Foo and Bar have the same underlying bit pattern.