If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In C language, a void pointer (also known as a generic pointer) is a pointer that can point to any type of data. This is achieved by declaring a pointer with a void type, which is represented by the keyword "void".
Here is an example of a void pointer:
Copy code
#include <stdio.h>
int main() {
int x = 10;
void* p = &x; // p is a void pointer pointing to the memory location of x
printf("%d\n", *(int*)p); // Dereference the void pointer as an int pointer
return 0;
}
In this example, the void pointer p is set to point to the memory location of the integer variable x. To access the value stored at that memory location, the void pointer must first be casted to a pointer of the appropriate type, in this example, it's casted to an int pointer, then it can be dereferenced to get the value of x.
Void pointers can be useful when working with generic data structures or functions that can operate on data of any type. For example, a function that takes a void pointer and a size as arguments can be used to copy a block of memory of any type.
Copy code
#include <stdio.h>
#include <string.h>
void copy_memory(void* dest, const void* src, size_t size) {
memcpy(dest, src, size);
}
int main() {
int x = 10;
int y = 20;
copy_memory(&y
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform
Didn't find what you're looking for?
Contact Support