Void and Null pointers in C

05 min read

Void pointers: These are general purpose pointers which do not have any type associated with them and can contain the address of any type of variable. So basically, the type of data that it points to can be anything.

  • Void pointers cannot be dereferenced unless it is typecasted to some other pointer type.
  • Pointer arithmetic is not possible on pointers of void due to lack of concrete value.

Example:

int n=10;
char c='A';
void *p;
p=&n;
printf("%d", *(int*)p);       //output: 10
p=&c;
printf("%c", *(char *)p);     //output: A

Hence we need not declare pointers for every data type. A single void pointer can be used to store the address of any type of variable and late be dereferenced.

Null pointers:  NULL Pointer is a pointer which is points to nothing. In case, if we don’t have the address to be assigned to a pointer, then we can simply use NULL.

Example:

int main()
{
int *ptr = NULL;
printf("The value of ptr is %d", ptr); //Value of ptr is 0
return 0;
}



Check out Dangling pointer here - https://www.faceprep.in/procoder/knowledgebase/dangling-pointer-in-c/

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error