Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment to un-initialised Integer Pointer

How is the value 2 being stored since the pointer has not been initialised in the following code snippet ?

int *p;
*p = 2;
printf("%d %d\n",p,*p);

The Output for the above program is as follows :

0 2

I was reading "Expert C Programming" by Peter Linden, and found this :

float *pip = 3.141; /* Wont compile */

But then how is the above program giving an output ? Is it because of using GCC ? or am I missing something ?

EDIT

I understand why float *pip = 3.141 is not valid, since an address location has to be an integer. So does this mean that p stores the memory address '0' and the value of '2' is being assigned to this address? Why is there no segmentation fault in this case?

like image 341
Kyuubi Avatar asked Apr 22 '26 04:04

Kyuubi


1 Answers

float *pip = 3.141;

pip is a pointer, a pointer must be initialized with an address (not with a value)

e.g:

float f[] = {0.1f, 0.2f, 3.14f};
float *pip = &f[2];
printf("%f\n", *pip);

EDIT:

Another one:

int *p = malloc(sizeof(int)); /* allocates space */
*p = 2; /* Now you can use it */
printf("%p %d\n", (void *)p, *p);
free(p);
like image 189
David Ranieri Avatar answered Apr 24 '26 20:04

David Ranieri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!