For working professionals
For fresh graduates
More
1. Introduction
6. PyTorch
9. AI Tutorial
10. Airflow Tutorial
11. Android Studio
12. Android Tutorial
13. Animation CSS
16. Apex Tutorial
17. App Tutorial
18. Appium Tutorial
21. Armstrong Number
22. ASP Full Form
23. AutoCAD Tutorial
27. Belady's Anomaly
30. Bipartite Graph
35. Button CSS
39. Cobol Tutorial
46. CSS Border
47. CSS Colors
48. CSS Flexbox
49. CSS Float
51. CSS Full Form
52. CSS Gradient
53. CSS Margin
54. CSS nth Child
55. CSS Syntax
56. CSS Tables
57. CSS Tricks
58. CSS Variables
61. Dart Tutorial
63. DCL
65. DES Algorithm
83. Dot Net Tutorial
86. ES6 Tutorial
91. Flutter Basics
92. Flutter Tutorial
95. Golang Tutorial
96. Graphql Tutorial
100. Hive Tutorial
103. Install Bootstrap
107. Install SASS
109. IPv 4 address
110. JCL Programming
111. JQ Tutorial
112. JSON Tutorial
113. JSP Tutorial
114. Junit Tutorial
115. Kadanes Algorithm
116. Kafka Tutorial
117. Knapsack Problem
118. Kth Smallest Element
119. Laravel Tutorial
122. Linear Gradient CSS
129. Memory Hierarchy
133. Mockito tutorial
134. Modem vs Router
135. Mulesoft Tutorial
136. Network Devices
138. Next JS Tutorial
139. Nginx Tutorial
141. Octal to Decimal
142. OLAP Operations
143. Opacity CSS
144. OSI Model
145. CSS Overflow
146. Padding in CSS
148. Perl scripting
149. Phases of Compiler
150. Placeholder CSS
153. Powershell Tutorial
158. Pyspark Tutorial
161. Quality of Service
162. R Language Tutorial
164. RabbitMQ Tutorial
165. Redis Tutorial
166. Redux in React
167. Regex Tutorial
170. Routing Protocols
171. Ruby On Rails
172. Ruby tutorial
173. Scala Tutorial
175. Shadow CSS
178. Snowflake Tutorial
179. Socket Programming
180. Solidity Tutorial
181. SonarQube in Java
182. Spark Tutorial
189. TCP 3 Way Handshake
190. TensorFlow Tutorial
191. Threaded Binary Tree
196. Types of Queue
197. TypeScript Tutorial
198. UDP Protocol
202. Verilog Tutorial
204. Void Pointer
205. Vue JS Tutorial
206. Weak Entity Set
207. What is Bandwidth?
208. What is Big Data
209. Checksum
211. What is Ethernet
214. What is ROM?
216. WPF Tutorial
217. Wireshark Tutorial
218. XML Tutorial
A void pointer is a generic pointer that can carry the address of any data type without defining its specific type, in contrast to other pointer types. Because of their adaptability, void pointers are beneficial in scenarios where the data type is unknown or subject to change over time.
However, you cannot directly dereference or use pointer arithmetic on a void pointer since it lacks information about the type it points to. You must first cast a void pointer to the proper data type to retrieve the data it points to.
In this article, let's learn in detail about what is a void pointer in C, what is a generic pointer in C, a generic pointer in C example, and many more!
In situations when the data type is unknown beforehand or may change dynamically while the application is running, void pointers are most commonly used. They are frequently used in low-level programming, as well as in the creation of generic data structures and multi-data type functions. However, since they do not provide type safety, utilizing void pointers calls for caution. To prevent memory access issues and undefined behavior, it is imperative to ensure proper casting while working with void pointers.
You normally get a memory address to utilize a void pointer by getting the address of a variable or by using dynamic memory allocation routines like malloc(). You must cast the void pointer to the proper data type before dereferencing it if you need to access the data it points to. Incorrect memory access can cause incorrect casting, which can cause program crashes or data corruption.
Void pointers offer a flexible way to interact generically and dynamically with various data types. To enable secure and dependable code execution, their use necessitates a thorough understanding of memory management and appropriate casting.
A void pointer in C++ can point to an object of any data type and is denoted by the symbol void*. A void pointer in C++ does not have a corresponding data type. It can therefore store any type of object's memory location, but it is unaware of the amount or structure of the data it links to.
As they are generic, void pointers are frequently employed when dealing with functions or data structures that need to handle a variety of data types or when the precise data type is unknown. For instance, void pointers are used in some libraries or APIs that require working with data of many types as a way to send data around without being constrained to a particular type.
There is a restriction when utilizing void pointers, though. You cannot directly dereference or use pointer arithmetic on the void pointer since the compiler is unaware of the sort of data it is pointing to. You must first cast the void pointer to the right data type to retrieve the data it points to. For proper memory access and accurate data interpretation, this casting is necessary.
In C programming, a void pointer (also known as a "generic pointer") is a special pointer type that can hold the address of any data type, including functions. It is used when you want to create a pointer without specifying its data type upfront. However, because the data type is not known at compile time, you need to cast the void pointer to the appropriate type before dereferencing it.
The syntax of a void pointer in C is as follows:
void *ptr;
Here, ptr is a void pointer that can hold the address of any data type. To use this pointer, you typically need to cast it to the correct data type before performing any operations on it.
For example:
int num = 42;
float value = 3.14;
void *ptr;
ptr = #
printf("Value at ptr: %d\n", *((int *)ptr));
ptr = &value;
printf("Value at ptr: %f\n", *((float *)ptr));
In this example, the void pointer ptr is first assigned the address of an integer (num), and then the address of a float (value). Before dereferencing the void pointer, it is cast to the appropriate data type (int or float).
Code:
#include <stdio.h>
int main()
{
int p = 12;
void* pt = &p;
printf("%d", *(int*)pt);
return 0;
}
In most C implementations, the size of a void pointer (void *) is the same as the size of a regular pointer to an object of any data type. This size depends on the architecture and compiler you're using.
Commonly:
However, the actual size can vary depending on the specific system and compiler settings. To determine the size of a void pointer on your system, you can use the sizeof operator:
Code:
#include <stdio.h>
int main() {
printf("Size of void pointer: %zu bytes\n", sizeof(void *));
return 0;
}
Void pointers (void *) in C offer several advantages in certain programming scenarios:
Code:
#include <stdio.h>
#include<malloc.h>
int main()
{
int k=80;
int *p = (int*)malloc(sizeof(int)) ;
p=&k;
printf("Value which is pointed by p pointer : %d",*p);
return 0;
}
We cannot dereference the void pointer in C directly. See the example,
Code:
#include <stdio.h>
int main()
{
int x=90;
void *ptr;
ptr=&x;
printf("Value which is pointed by ptr pointer : %d",*ptr);
return 0;
}
In this code, *ptr is a void pointer that points to the integer variable 'x'. We know that void pointers can’t be dereferenced, so in this code will give the compile-time error because we are printing the value of the variable pointed by the pointer 'ptr' directly.
In this above code, we typecast the void pointer to the integer pointer by using the statement given below:
(int*)ptr;
After that, we are able to print the values of the variables that are pointed by the void pointers 'ptr' by using the statement given below:
*(int*)ptr;
Now, we are rewriting the above code to remove the error:
Code:
#include <stdio.h>
int main()
{
int x=80;
void *ptr;
ptr=&x;
printf("Value which is pointed by ptr pointer : %d",*(int*)ptr);
return 0;
}
In C We cannot apply the arithmetic operations on void pointers. We have to apply the proper typecasting to perform the arithmetic operations on the void pointers.
See the example:
Code:
int main()
{
float p[4]={6.1,2.3,7.8,9.0};
void *ptr;
ptr=p;
for(int i=0;i<4;i++)
{
printf("%f,",*ptr);
ptr=ptr+1; // Incorrect.
}}
This program above shows the error "invalid use of void expression" during compilation as we are not able to apply arithmetic operations on void pointers directly, i.e., ptr=ptr+1.
Now, we are rewriting the above code to remove the error:
Code:
#include<stdio.h>
int main()
{
float p[4]={6.1,2.3,7.8,9.0};
void *ptr;
ptr=p;
for(int i=0;i<4;i++)
{
printf("%f,",*((float*)ptr+i));
}}
Void pointers are used for several reasons in C and C++ programming. They:
Generic Programming: Using void pointers, a single function or data structure can be used to operate with several data types in generic programming. This is especially helpful if you want to write reusable code that can handle different data types without having to write separate pieces of code for each kind.
Dynamic Memory Allocation: With dynamic memory allocation functions like malloc() or calloc() in C and new operators in C++, void pointers are frequently employed. The correct data type must be returned to its previous forms before accessing any allocated memory.
Function Pointers: Function pointers can be converted to and from void pointers in C and C++. You use this capability to store them in data structures is one of the biggest use of void pointers in C. You can store numerous function pointers with varied signatures in a single data structure by casting to a void pointer.
Interfacing with External Libraries: You must utilize void pointers to send or receive data when interacting with external libraries or APIs that use them to pass data. You can accurately extract or analyze the data by casting to the proper data type.
Memory Manipulation: Void pointers are sometimes used for low-level memory manipulation or type punning. However, using void pointers for these purposes requires careful consideration and adherence to strict-aliasing rules to avoid undefined behavior.
Despite their adaptability, void pointers come with significant hazards. Improper casting or dereferencing can result in memory problems, crashes, or data corruption because the type of information is not retained. It is crucial to handle void pointers carefully, provide proper type management, and maintain memory safety.
Overall, a void pointer is a useful tool for C programmers, but using it effectively needs a solid grasp of memory management, type casting, and adherence to best practices. Void pointers can considerably increase the adaptability and versatility of C programs when utilized wisely and carefully.
In conclusion, void pointers (void*) are essential in C programming because they provide a strong and adaptable framework for handling data of varied or ambiguous kinds. When generic programming is required, void pointers are crucial because they may hold any data type in a single pointer. They make it possible to develop generic algorithms and data structures that can be applied to various data types, encouraging the modularity and maintainability of the code.
In C or C++, you cannot directly dereference or execute pointer arithmetic on a void pointer ('void*'). Additionally, until you explicitly convert the data to the correct data type, you cannot access the data it points to. To access the underlying data safely, void pointers must first be cast to the correct type because they lack type information.
The delete operator in C++ or the free() function in C cannot calculate the proper deallocation size for a void pointer because it lacks type information. You must first convert memory allocated via a void pointer to the relevant data type before using the proper deallocation function (such as delete for C++ objects or free() for dynamically allocated memory) to properly release the memory.
The size of a void pointer ('void*') in C depends on the platform. It normally has the same size as a system regular pointer, which on a 32-bit system is typically 4 bytes and on a 64-bit system is often 8 bytes. The void pointer can point to any sort of object because it is made to contain memory addresses rather than being tied to any particular data type.
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.