Search code examples
c++pointersequalityvoid

Comparison between void pointers in C++


What's the size of the pointed memory by a void pointer?

In the example below, I'm comparing two void pointer that are pointing to the same "raw data" but with different type so different size...how it can works? Is it linked to the == operator?

#include <iostream>

using namespace std;

int main()
{
    char a = 'a';
    int b = 97;
    if ((void*)a == (void*)b){
        cout << sizeof(a) << sizeof(b) << endl;
    }
}

Solution

  • I'm comparing two void pointer that are pointing to the same "raw data" but with different type so different size...how it can works? Is it linked to the == operator?

    That is not exactly what you are doing. You are interpreting char and int values as pointers to void. Size does not matter at all in this case.

    You are nicely demonstrating one reason why not to use C-style cast - it not being clear what it is doing exactly. The rules can be found e.g. on cppreference. In your case it uses reinterpret_cast which should be a red flag had you seen it in the code in the first place.

    Casting an integer to a pointer is a way how to point to specific memory address, which is far from what you want. But the comparison will most likely be true since 'a' is usually 97 (0x61). So you are effectively asking 0x61==0x61.

    To answer you question

    What's the size of the pointed memory by a void pointer?

    , which is not related to the code you posted, it is platform-specific, most probably 4 or 8 bytes.