0

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;
    }
}
  • 1
    Could you please clarify what are you trying to achieve? – Suthiro Nov 22 '20 at 09:56
  • 3
    The size of pointer will depend on whether your app is 32-bit or 64-bit. For 32-bit apps, it will be 4 bytes and for 64-bit it will be 8 bytes – Asesh Nov 22 '20 at 09:56
  • That comparison will always be true. See also [this question](https://stackoverflow.com/questions/1975128/why-isnt-the-size-of-an-array-parameter-the-same-as-within-main) and the [reference for `sizeof`](https://en.cppreference.com/w/cpp/language/sizeof). – Lukas-T Nov 22 '20 at 10:22

1 Answers1

2

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.

Quimby
  • 17,735
  • 4
  • 35
  • 55