What exactly does a pointer store?

Published

2023-08-05

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!

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

All materials copyright © 2020–2023, The University of Vermont. All rights reserved.