Trying to figure out the difference between pointer initialization and pointer assignment.
C language
int *p=0;
int *p;
*p=0;
I don't know what is the difference between the two methods. Same?
Within a function,
int *p = 0;
is equivalent to:
int *p;
p = 0;
I.e. the variable itself is initialized, with the declarator portion of the declaration being ignored. As opposed to:
int *p;
*p = 0;
which results in undefined behavior since the target of an undefined pointer is being assigned to.
The main reason why every new C programmer struggles with pointers is the similar-looking syntax between pointer declaration and pointer access/de-referencing.
int *p;
is a declaration of a pointer to integer. *p=0;
is de-referencing the pointer, accessing the location it points at and attempting to write the value 0 there. For this to be ok, the pointer must be set to point at a valid memory location first.int *p = 0;
is a declaration of a pointer to integer, with an initializer value. This sets where the pointer itself points at. It is not de-referencing.Assigning/initializing the value 0
to the pointer itself is a special case, since this translates to a "null pointer constant". Basically a pointer pointing at a well-defined nowhere. It is preferred to use the macro NULL
from stddef.h instead, so that we don't mix it up with the integer value 0
.
Because in the case of *p=0;
on a line of its own, the 0
is just that, a plain integer value.
Also see Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With