Reputation: 2679
Lets have an array of type int:-
int arr[5];
Now,
if arr[0] is at address 100 then
Why do we have;
arr[1] at address 102 ,
arr[2] at address 104 and so on.
Instead of
arr[1] at address 101 ,
arr[2] at address 102 and so on.
Is it because an integer takes 2 bytes?
Does each memory block has 1 Byte capacity (whether it is 32 bit processor or 64 bit)?
Upvotes: 1
Views: 114
Reputation: 9590
You are right, on your machine the sizeof int is 2, so next possible value in the array will be 2 bytes away from the previous one.
-------------------------------
|100|101|102|103|104|105|106....
-------------------------------
arr[0] arr[1] arr[2]
There is no guaranty regarding size of int
. C++ spec just says that sizeof(int) >= sizeof(char). It depends upon processor, compiler etc.
For more info try this
Upvotes: 0
Reputation: 500157
Your first example is consistent with 16-bit ints
.
As to your second example (&arr[0]==100
, &arr[1]==101
, &arr[2]==103
), this can't possibly be a valid layout since the distance between consecutive elements varies between the first pair and the second.
Upvotes: 3
Reputation: 35039
It is because an integer takes 2 bytes?
Yes
Apparently on your system, int
has the size of 2. On other systems, this might not be the case. Usually int
is either sized 4 or 8 bytes, but other sizes are possible also.
Upvotes: 3