0
#include <iostream> #include <string> #include <cmath> using namespace std; int main() { int a = 5; int b = &a; } 

Why doesn't this work? If I make b a pointer like int *b = &a then that'll work but if a memory address is just an integer in hexadecimal then why is this not okay?

8
  • 2
    One reason is int may be smaller than a pointer. This is the case on 64 bit msvc where int is 32 bits and pointers are 64 bits. Commented Aug 27, 2021 at 17:26
  • 1
    Because an int isn't a pointer. Why do you want to store a pointer in a integer? Commented Aug 27, 2021 at 17:26
  • 7
    Because that is what type safety is for. They're both integers but semantically different (and might take up different sizes of memory). In fact, float, double, int, string, etc. are all just binary numbers. But we give them a type to tell the compiler how we want to use them. Then the compiler warn us if we try to use them differently than we have declared. Commented Aug 27, 2021 at 17:26
  • 1
    A pointer is the address. It just has a funky spelling and type. Commented Aug 27, 2021 at 17:35
  • 2
    "a memory address is just an integer in hexadecimal". "Hexadecimal" is a writing style. It's a way to print a number. No count or quantity of anything is intrinsically hexidecimal. Commented Aug 27, 2021 at 17:48

2 Answers 2

6

Well, first off, the sizes may not match; most general purpose computers nowadays use 64 bit addressing, but most compilers provide 32 bit ints (historically, some early 32 bit computers had 32 bit pointers but still provided 16 bit ints; this isn't a new problem).

It's also discouraged because it's usually an error (someone forgot to declare a variable as a pointer).

If you want a variable that is guaranteed to be able to fit a pointer, but acts like an integer, you can use intptr_t or uintptr_t, you just need to cast it to say "yep, I really meant to use this pointer as an integer".

Sign up to request clarification or add additional context in comments.

Comments

1

It's not an integer in hexadecimal.

First of all, hexadezimal is just a possible output encoding, and the very same variable is also suitable for any other encoding, be it octal, decimal or binary. The native representation is binary in any case.

Next up, pointers and integral values are differentiated in the language design by choice, as a mix-up usually has bad consequences. Pointer also use pointer-arithmetic, which differs from integer arithmetic. E.g. (int*)(0) + 1 == (int*)( 0 + sizeof(int)).

Finally, that int is only 32bit, while the pointer, depending on the target architecture, requires 64bit, so this won't even fit, even if the compiler did allow that cast.

1 Comment

We don't know that the int mentioned is 32-bits and I see no mention of address representation as text (maybe question changed). Your answer just seems slightly off.