Amir Hasan Amir Hasan - 22 days ago 7
C Question

Assigning decimal zero to a C pointer

//line 2 causes the program to terminate
#include <stdio.h>
int main()
{
int *qi = 0; //1 -- making qi a null pointer
if(qi==NULL) printf("Null\n");
else printf("Not Null\n");
*qi =0; // 2 --- assigning *qi a decimal zero value.
return 0;
}


comment number 2 in the above code terminates the program whereas adding one line

qi = &zero;


in the above code, before comment number 2 prevents this as shown below

// this code works fine
#include <stdio.h>
int main()
{
int *qi = 0; //1
if(qi==NULL) printf("Null\n");
else printf("Not Null\n");
int zero =0;
qi = &zero;
*qi= zero; //2
printf("%d\n",*qi);
return 0;
}


why is this happening? Explain as if you are explaining to a child.

Answer

it is simple... an integer pointer points to block of memory allocated by an integer. A null pointer has no memory to point. so by *qi =0; you are de refrencing a null location, which actually does not exist. And in your second case you point your integer pointer to an integer variable zero so that works.