Yatharth
Yatharth

Reputation: 15

void pointer and its assignment to the void datatype

The problem is using void datatype and assigning some value to the void variable.

#include<stdio.h>
#include<stdlib.h>
int main()
{
 void *pVoid;
 pVoid = (void*)0;
 printf("%lu",sizeof(pVoid));
 return 0;
}

what is assigned to pVoid in second line.

Upvotes: 3

Views: 343

Answers (2)

dbush
dbush

Reputation: 223917

pVoid is assigned the value NULL. This is because the expression (void*)0 is defined as a null pointer constant.

Section 6.3.2.3p3 of the C standard states:

An integer constant expression with the value 0, or such an expression cast to type void * , is called a null pointer constant . If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

Upvotes: 1

m.raynal
m.raynal

Reputation: 3113

Copied directly from the standard library wiki:

Defined in stddef.h, locale.h, stdio.h, stdlib.h, string.h, time.h.

In standard C, this can be implemented as:

#if !defined(NULL)
    #define NULL ((void*)0)
#endif

So pVoid get assigned exactly what it would get assigned with NULL on the second line.

Edit: as mentioned by @Jens Gustedt in comments, it is good to note that this implementation of NULL is not unique, and can be platform-dependent.

Upvotes: 2

Related Questions