Amir Hasan Amir Hasan - 1 year ago 57
C Question

What is the difference between the assignments to pointers in C?

//C - code
int num
int *pi = # //1
printf(" *pi=%d and pi=%d \n ", *pi, pi); // p1
pi = # //2
printf(" *pi=%d and pi=%d \n ", *pi, pi); // p2

As for comment
, I understand that we are assigning a valid address to the pointer pi but I don't understand what is happening in the line of comment
because because both the
are doing the same job.

And in case of dynamic memory management with malloc(sizeof(datatype)) function, why the following is an invalid approach?

int *pi;
*pi = (int*)malloc(sizeof(int)); // terminates the program

while the following:

int *ri = (int*)malloc(sizeof(int));


int *qi;
qi = (int*)malloc(sizeof(int));

works fine.

Please explain.

EDIT: The question marked as duplicate to this question doesn't talk about pointers and problems that we face during dynamic memory management.

Answer Source

You are getting confused between the use of * in the declaration of a pointer and the use of * as the dereferencing operator.

To understand better, while declaring, you can write int *p as (int*) p. This means, that p is of type 'pointer to an int'.

However, * is also the dereferencing operator, or the 'value at' operator. So, *pi = value at pi, i.e., the value stored at the location of num, i.e., the value of num.

int *pi;
*pi = (int*)malloc(sizeof(int));

crashes becuse you try to assign the result of (int*)malloc(sizeof(int)) to the location where pi is pointing. but as pi is not pointing anywhere (it is uninitialized), hence, it doesn't work.

On the other hand,

int *ri = (int*)malloc(sizeof(int)); 

works because you are making ri point to the location where the result of (int*)malloc(sizeof(int)); is stored.

int *qi;
qi = (int*)malloc(sizeof(int));

also works because you are making qi point to the location where (int*)malloc(sizeof(int)); is stored.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download