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 ?
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?
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);