热心的水煮鱼 · JSON Primitive Types ...· 4 月前 · |
想出家的电梯 · 张俪(中国内地女演员)_百度百科· 4 月前 · |
骑白马的领带 · 2022中国千人汽车拥有量226,超巴西近泰 ...· 4 月前 · |
千杯不醉的仙人球 · 社保部门提醒:员工离职不要轻易断缴社保 可自行缴费· 4 月前 · |
飘逸的鞭炮 · verilog ...· 6 月前 · |
A void pointer is a pointer that has no associated data type with it. A void pointer can hold an address of any type and can be typecasted to any type.
// C Program to demonstrate that a void pointer
// can hold the address of any type-castable type
#include <stdio.h>
int
main()
int
a = 10;
char
b =
'x'
;
// void pointer holds address of int 'a'
void
* p = &a;
// void pointer holds address of char 'b'
p = &b;
Time Complexity:
O(1)
Auxiliary Space:
O(1)
1. void pointers cannot be dereferenced.
Example
The following program doesn’t compile.
Output
Compiler Error: 'void*' is not a pointer-to-object type
The below program demonstrates the usage of a void pointer to store the address of an integer variable and the void pointer is typecasted to an integer pointer and then dereferenced to access the value. The following program compiles and runs fine.
void
* ptr = &a;
// The void pointer 'ptr' is cast to an integer pointer
// using '(int*)ptr' Then, the value is dereferenced
// with `*(int*)ptr` to get the value at that memory
// location
printf
(
"%d"
, *(
int
*)ptr);
return
0;
Time Complexity:
O(1)
Auxiliary Space:
O(1)
2. The C standard doesn’t allow pointer arithmetic with void pointers. However, in GNU C it is allowed by considering the size of the void as 1.
Example
The below C program demonstrates the usage of a void pointer to perform pointer arithmetic and access a specific memory location. The following program compiles and runs fine in gcc.
// C program to demonstrate the usage
// of a void pointer to perform pointer
// arithmetic and access a specific memory location
#include <stdio.h>
int
main()
// Declare and initialize an integer array 'a' with two
// elements
int
a[2] = { 1, 2 };
// Declare a void pointer and assign the address of
// array 'a' to it
void
* ptr = &a;
// Increment the pointer by the size of an integer
ptr = ptr +
sizeof
(
int
);
// The void pointer 'ptr' is cast to an integer
// pointer using '(int*)ptr' Then, the value is
// dereferenced with `*(int*)ptr` to get the value at
// that memory location
printf
(
"%d"
, *(
int
*)ptr);
return
0;
Time Complexity:
O(1)
Auxiliary Space:
O(1)
Note : The above program may not work in other compilers.
Following are the advantages of void pointers
想出家的电梯 · 张俪(中国内地女演员)_百度百科 4 月前 |