I’m trying to understand what this code does (and if it’s even allowed):
int * A;
int * B;
A = (int *)malloc( size_t somenumber );
B = A;
// bunch of stuff using B, B++, etc.
Everything I’ve read always shows equating things to pointers either using the reference operator (&) or the derefernce operator (*).
What does this sort of equating do?
And, when I ultimately free(A) what happens to B?
Pictures are always good when it comes to pointer confusion:
Conceptually:
So after all that I think you can see what’s happening. B is being assigned the value of A, which is the allocated and uninitialized memory chunk. So now you just have two pointers pointing to the same area.
As to the
free()question, as you can see when you callfree(A);you’re left with both A and B pointing to the same area, there’s just nothing allocated to your program there anymore. This is why when callingfree()it’s good to set your pointer toNULL.Now way back to your initial question. If you wanted to check of two pointers were
==:UPDATE
So to answer your updated questions, We need to change the definition of
B.So to illustrate that:
For
B=*A:This is a deference of
A. So you’re just taking whatever A is pointing to and assigning it toB, in this case 5