Search code examples
cpointersinitializing

Pointer initialization concept in C


Why is this erroneous?

char *p;   
*p='a';

The book only says -use of uninitialized pointer. Please can any one explain how that is?


Solution

  • char *c; //a pointer variable is being declared 
    *c='a';
    

    you used the dereferencing operator to access the value of the variable to which c points to but your pointer variable c is not pointing to any variable thats why you are having runtime issues.

    char *c; //declaration of the pointer variable
    char var; 
    c=&var; //now the pointer variable c points to variable var.
    *c='a'; //value of var is set to 'a' using pointer 
    printf("%c",var); //will print 'a' to the console
    

    Hope this helped.