Reputation: 5762
Learner question. I can declare and initialize a pointer in two different way
int a = 10;
int *p = &a;
also
int a = 10;
int *q;
q = &a;
I want to know what is the difference between two and how does it work in the memory?
Upvotes: 2
Views: 11985
Reputation: 182639
The first one is initialization while the second one is assignment. Technically they are both very different operations that happen to use the same operator, with very different meanings - in C the =
sign is, if you will, "overloaded".
In this case it will translate into the same behavior.
The standard defines them separately. In this case there are no differences but sometimes there are. For example when the object has static storage you can initialize it only to literals and constant expressions, while you can easily assign other stuff to it. There are more differences and it all boils down to the fact that they are different operations that for some reason use the same sign.
Upvotes: 3
Reputation: 11629
Those two are the same :
int *p; // declaration
p = &a; // assignment
and in the other you are combining the two steps together into one:
int *p=&a; // declaration and assignment
And if you have some compiler optimizations ON, the compiler might combine the two steps.
Upvotes: 5
Reputation: 344
There is no difference as such in both ways. Both do the same thing.
In first you are initializing at the time of declaration. In next one, you defer initialization.
both are doing the same thing i.e. storing address of variable 'a'.
About how does it work in memory. 'a' has its memory allocated(2/4 bytes) and stores its value at this location. The address of the first byte is stored in 'p'/'q' using &a(i.e address of a) which itself has memory allocated.
To retrieve value using pointer, you can use *p/*q(i.e. value at the address stored in p)
Upvotes: 0
Reputation: 370132
Your two pieces of code are equivalent - there is no difference.
Generally for any type T
, any variable name x
and any expression exp
, T x = exp;
and T x; x = exp;
are equivalent to each other.
Upvotes: 3