English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ pointer to viod (null pointer)

In this article, you will learn how to use null pointers. These pointers can point to any type of data. This article will teach you how to use them effectively in a program.

in C ++in it, you cannot assign the address of a variable of one type to another typepointer. See the following example:

int *ptr;
double d = 9;
ptr = &d;   // Error: cannot assign double*assignment to int

However, there is an exception.

in C ++in it, there is a general-purpose pointer that can point to any type. This general-purpose pointer is a void pointer.

void *ptr; // pointer to void

Example1: pointing to C void ++pointer

#include <iostream>
using namespace std;
int main() {
    void* ptr;
    float f = 2.3;
    ptr = &f;     // float* to void
    cout << &f << endl;
    cout << ptr;
    return 0;
}

Output Result

0xffd117ac
0xffd117ac

Here, the value of the pointer ptr is &f.

The output shows that the void pointer ptr stores the address of a floating-point variable f.