Void Pointers
This is a special type of pointer available in C++ which represents the absence of type. Void pointers are pointers that point to a value that has no type (and thus also an undetermined length and undetermined dereferencing properties). This means that void pointers have great flexibility as they can point to any data type. There is a payoff for this flexibility. These pointers cannot be directly dereferenced. They have to be first transformed into some other pointer type that points to a concrete data type before being dereferenced.
// C++ program to illustrate Void Pointer
#include <bits/stdc++.h>
using namespace std;
void increase(void* data, int ptrsize)
{
if (ptrsize == sizeof(char)) {
char* ptrchar;
// Typecast data to a char pointer
ptrchar = (char*)data;
// Increase the char stored at *ptrchar by 1
(*ptrchar)++;
cout << "*data points to a char"
<< "\n";
}
else if (ptrsize == sizeof(int)) {
int* ptrint;
// Typecast data to a int pointer
ptrint = (int*)data;
// Increase the int stored at *ptrchar by 1
(*ptrint)++;
cout << "*data points to an int"
<< "\n";
}
}
void geek()
{
// Declare a character
char c = 'x';
// Declare an integer
int i = 10;
// Call increase function using a char and int address
// respectively
increase(&c, sizeof(c));
cout << "The new value of c is: " << c << "\n";
increase(&i, sizeof(i));
cout << "The new value of i is: " << i << "\n";
}
// Driver program
int main() { geek(); }
Output
*data points to a char The new value of c is: y *data points to an int The new value of i is: 11
C++ Pointers
Pointers are symbolic representations of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. Iterating over elements in arrays or other data structures is one of the main use of pointers.
The address of the variable you’re working with is assigned to the pointer variable that points to the same data type (such as an int or string).
Syntax:
datatype *var_name;
int *ptr; // ptr can point to an address which holds int data