简体   繁体   中英

Why am I getting different addresses when using similar logic to increment two different pointer types?

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM