简体   繁体   中英

c++ pointer arithmetic

int a[5];

cout << &a[1] << " " << &a[0] << endl;
cout << (&a[1] - &a[0]);

In the above code, why is &a[1] - &a[0] equal to 1 and not 4? Shouldn't there be 4 bytes between these addresses since we have an int array?

不,指针差异在元素中,而不是以字节为单位。

Pointers are incremented by the size of there type. Reason is because you want to point to the next item. So taking you example further.

int a[5];
int *ptr=&a[0];

// ptr is now pointing at first element.

ptr+3; // now its pointing at 3rd element.

To get it in bytes: (see it live https://ideone.com/CrL4z )

int a[5];

cout << (a+1) << " " << (a+0) << endl;
cout << (reinterpret_cast<char*>(a+1) - reinterpret_cast<char*>(a+0));

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