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).
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:
Possible output:
In memory it looks like this:
It doesn't. Don't confuse pointers with what they point too.
inttaking up 4 bytes and a pointer toint, aint*, 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 viasizeof(T)).