Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between "int *p =0;" and "int *p; *p=0;"

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?

like image 318
Joey Avatar asked Dec 05 '22 09:12

Joey


2 Answers

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.

like image 53
Tom Karzes Avatar answered Dec 28 '22 11:12

Tom Karzes


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.

like image 33
Lundin Avatar answered Dec 28 '22 12:12

Lundin