Reputation: 109
I am a university student currently studying computer science and programming and while reading chapter 2 of c++ primer by Stanley B. Lippmann a question popped up into my mind and that is, if computer memory is divided into tiny storage locations called Bytes (8 bits) and each Byte of memory is assigned a unique address, and an integer variable uses up 4 Bytes of memory, shouldn't my console, when using the address-of operator print out 4 unique addresses instead of 1?
I doubt that the textbook is incorrect and that their is a flaw in my understanding of computer memory. As a result, I would like a positive clarification of this question I am facing. Thanks in advance people :)
Upvotes: 1
Views: 87
Reputation: 9407
Yes an integer type requires four bytes. All four bytes are allocated as one block of memory
for your integer, where each block has a unique address. This unique address is simply the first byte's address of the block
.
Upvotes: 3
Reputation: 409216
Each variable is located in memory somewhere, so each variable gets an address you can get with the address-of operator.
That each byte in a multi-byte variable also have their addresses doesn't matter, the address-of operator gives you a pointer to the variable.
Some "graphics" to hopefully explain it...
Lets say we have an int
variable named i
, and that the type int
takes four bytes (32 bits, this is the usual for int
). Then you have something like
+---+---+---+---+ | | | | | +---+---+---+---+
Some place is reserved for the four bytes, where doesn't matter the compiler will handle all that for you.
Now if you use the address-of operator to get a pointer to the variable i
i.e. you do &i
, then you have something like
+---+---+---+---+ | | | | | +---+---+---+---+ ^ | &i
The expression &i
points to the memory position where the byte-sequence of the variable begins. It can't possible give you multiple pointers, one for each byte, that's really impossible, and not needed as well.
Upvotes: 5
Reputation: 171353
shouldn't my console, when using the address-of operator print out 4 unique addresses instead of 1?
No.
The address of an object is the address of its starting byte. A 4-byte int
has a unique address, the address of its first byte, but it occupies the next three bytes as well. Those next three bytes have different addresses, but they are not the address of the int
.
Upvotes: 6