Till now, we have studied that the address assigned to a pointer should be of the same type as specified in the pointer declaration. For example, if we declare the int pointer, then this int pointer cannot point to the float variable or some other type of variable, i.e., it can point to only int type variable. To overcome this problem, we use a pointer to void. A pointer to void means a generic pointer that can point to any data type.
Syntax of void pointer
In the above declaration, the void is the type of the pointer, and 'ptr' is the name of the pointer.
Let us consider some examples:
int i=9; // integer variable initialization.
int *p; // integer pointer declaration.
float *fp; // floating pointer declaration.
void *ptr; // void pointer declaration.
p=fp; // incorrect.
fp=&i; // incorrect
ptr=p; // correct
ptr=fp; // correct
ptr=&i; // correct
Size of the void pointer in C
The size of the void pointer in C is the same as the size of the pointer of character type. According to C perception, the representation of a pointer to void is the same as the pointer of character type. The size of the pointer will vary depending on the platform that you are using.
Let's look at the below example:
int main()
{
void *ptr = NULL; //void pointer
int *p = NULL;// integer pointer
char *cp = NULL;//character pointer
float *fp = NULL;//float pointer
//size of void pointer
printf("size of void pointer = %d\n\n",sizeof(ptr));
//size of integer pointer
printf("size of integer pointer = %d\n\n",sizeof(p));
//size of character pointer
printf("size of character pointer = %d\n\n",sizeof(cp));
//size of float pointer
printf("size of float pointer = %d\n\n",sizeof(fp));
return 0;
}
No comments:
Post a Comment