Void Pointers

Wasim Khan
Oct 24, 2020

Void pointers come in context when you have limited knowledge of what data type you are dealing with. They can be used with any data type.

Just remember not to de-reference void pointers. You have to cast them to specific pointer type before de-referencing.

int a = 5;
char b = 'b';
string str = "hello, world!";
vector<int> arr = {1, 2, 3, 4};
void* vptr = &a;
vptr = &b; // works just fine
// don't dereference without converting it back to specific type
cout << *(static_cast<char*>(vptr)) << endl;

When you ask malloc to allocate new memory of specific size, they return a void pointer. You have to convert them to specific pointer type to use the memory allocated. “new” returns the pointer for the specific type that you are allocating memory for.

Also if you need to copy from one memory region to another, you can use void pointers. That’s how memcpy works.

#include <iostream>
#include <string>
#include <bits/stdc++.h>
using namespace std;
void memcpy(void* src, void* target, size_t size){
// cast src and target to char pointers before you use them
char* csrc = static_cast<char*> (src);
char* ctarget = static_cast<char*> (target);
for(size_t i = 0; i < size; ++i)
ctarget[i] = csrc[i];
}
int main()
{
char* word1 = "hello, world!";
char* word2 = new char[strlen(word1)];
void *src = word1;
void *target = word2;
memcpy(src, target, strlen(word1));
for(int i = 0; i < strlen(word1); ++i) cout << *word2++;
return 0;
}

--

--