What exactly does a pointer store?
Q: What exactly does a pointer store?
A: A pointer stores a memory address.
Q: Does a pointer store the type of object pointed to?
A: Not exactly, but it’s OK to think of it that way informally. The type is not “stored,” per se. The type of the object pointed to is encoded in the pointer’s type. So a int*
stores a pointer to an int
, a float*
stores a pointer to a float
and so on.
Here’s an example showing how to trick C++ into interpreting a pointer as a different type (this is bad, so don’t do this in your code).
#include <iostream>
int main() {
int x = 36; // 36 is the ASCII code for the $ symbol
void *xPtrVoid = &x; // now we create a void pointer; a pointer without a type
char *xPtrChar = (char *) xPtrVoid; // now we cast void pointer as char pointer
std::cout << *xPtrChar << std::endl; // prints $
return 0;
}
Again, this is for illustration purposes only. Don’t do this!
Copyright © 2023–2025 Clayton Cafiero
No generative AI was used in producing this material. This was written the old-fashioned way.