void pointer in C
void pointer in C
A void pointer is a pointer that has no associated data type with
it. A void pointer can hold address of any type and can be typcasted to
any type.
Advantages of void pointers:int a = 10;char b = 'x';void *p = &a; // void pointer holds address of int 'a'p = &b; // void pointer holds address of char 'b' |
1) malloc() and calloc() return void * type and this allows these functions to be used to allocate memory of any data type (just because of void *)
int main(void){ // Note that malloc() returns void * which can be // typecasted to any type like int *, char *, .. int *x = malloc(sizeof(int) * n);} |
2) void pointers in C are used to implement generic functions in C. For example compare function which is used in qsort().
Some Interesting Facts:
1) void pointers cannot be dereferenced. For example the following program doesn’t compile.
#include<stdio.h>int main(){ int a = 10; void *ptr = &a; printf("%d", *ptr); return 0;} |
Compiler Error: 'void*' is not a pointer-to-object typeThe following program compiles and runs fine.
#include<stdio.h>int main(){ int a = 10; void *ptr = &a; printf("%d", *(int *)ptr); return 0;} |
102) The C standard doesn’t allow pointer arithmetic with void pointers. However, in GNU C it is allowed by considering the size of void is 1. For example the following program compiles and runs fine in gcc.
#include<stdio.h>int main(){ int a[2] = {1, 2}; void *ptr = &a; ptr = ptr + sizeof(int); printf("%d", *(int *)ptr); return 0;} |
2
Comments
Post a Comment