I am currently learning pointers in c. I have learned that if I do not assign an address to a pointer and try to print the value of the content of the pointer, then the program will not run properly.
#include <stdio.h>
int main()
{
double *q;
printf("Hello World\n");
printf("*q = %lf", *q);
return 0;
}
For example, the code given above will print 'Hello World' and then return something other than 0, ignoring the 2nd printf() function altogether. Here is the output.
However, things get interesting if a null pointer is included in the code.
#include <stdio.h>
int main()
{
double *p = NULL, *q;
printf("Hello World\n");
printf("*q = %lf", *q);
return 0;
}
Now, this is the output. To be honest, this output does not make any sense to me. I was expecting to get the same result as before but clearly that did not happen. How can an inclusion of a null pointer make *q = 0.000000? I am super confused. Please help me understand what is going on here.
Besides, does the output vary from device to device? I have a hunch that devices with Linux OS would yield a different output. My device has Windows 11 as its OS. Is the output different for other Windows (11 or others) users too? And maybe the value 0.000000 is a garbage value? I am kind of curious.
Thanks in advance.
qis somehow getting value pointing to the locationpis allocated at. Still garbage, but happens to be zero.*qremains undefined behavior or maybe indeterminate.%g,%eor%a, not%f. They are more informative when values are small. (e.g. the value might not be 0.0)