Search code examples
c++rammemory-address

How do addresses in C++ refer to multiple bytes as once?


Whenever I use C++, I can 'refer' to multiple bytes at once. For example:

char* charptr = new char;

This line allocates a new variable on the stack, pointer charptr, that points to 1 byte of data on the heap. This makes sense, since a physical address on my computer can store 1 byte.

However, confusion begins with a line of code like this:

int* intptr = new int;

This pointer contains only a single address to an 8-byte integer.

How can a single address store multiple bytes?

I have tried to search around StackOverflow, but could not find an answer, and I am left wondering how this works (I am trying to make a Little Man Computer style of model, and want to implement a high level language for it).


Solution

  • Pointers to objects point to the first byte of that object. That first byte doesn't store the whole object, but its just the first byte. How many bytes make up the object is determined by its type.

    For example:

    #include <iostream>
    
    int main(){
        int x = 42;
        std::cout << sizeof(int) << "\n";
        std::cout << &x << "\n";
    }
    

    Possible output:

    4
    0x7fff8612186c
    

    In memory it looks like this:

    [              int                                ]
    [ 1st byte ] [ 2nd byte ] [ 3rd byte ] [ 4th byte ]
     ^
     |
     &x
    

    How can a single address store multiple bytes?

    It doesn't. Don't confuse pointers with what they point too. int taking up 4 bytes and a pointer to int, a int*, holding the address of a single byte is no contradiction. The size of the memory block occupied by the object is encoded in its type (and can be queried via sizeof(T)).