Reputation: 396
I don't understand why the addresses of my floats go up by 16, when the size of my floats are 4. Could someone please explain?
Code:
char* mychar = new char[SIZE];
float* myfloat = new float[SIZE];
for(int i = 0; i < SIZE; i++)
{
mychar[i] = 'A' + i;
myfloat[i] = 101 + i;
}
for(int i = 0; i < SIZE; i++)
{
cout << setw(12) << "new char @ <" << static_cast<void*>(mychar) + sizeof(char)*i << ">=<" << mychar[i] << ">"
<< setw(14) << " new float @ <" << myfloat + sizeof(float)*i << ">=<" << myfloat[i] << ">\n";
}
cout<< "Size of float: " << sizeof(float) << endl << "Size of char: " << sizeof(char);
Output:
new char @ <0x800102e8>=<A> new float @ <0x800102f8>=<101>
new char @ <0x800102e9>=<B> new float @ <0x80010308>=<102>
new char @ <0x800102ea>=<C> new float @ <0x80010318>=<103>
new char @ <0x800102eb>=<D> new float @ <0x80010328>=<104>
Size of float: 4
Size of char: 1
Upvotes: 2
Views: 85
Reputation: 372664
Notice that myfloat
is a float*
. This means that if you write an expression like
myfloat + n
the result will be a pointer to the float
that is n
positions down in the array of float
s whose address starts at myfloat
. In other words, adding n
here will automatically increment the pointer by n * sizeof(float)
bytes, since pointer addition is aware of the size of the object.
Consequently, if you write
myfloat + n * sizeof(float)
you are not jumping forward by n * sizeof(float)
bytes, but rather than n * sizeof(float) * sizeof(float)
bytes, which happens to be 16n bytes.
Hope this helps!
Upvotes: 6