c++ - 为什么这两个指针之间的距离是3?
PHP中文网
PHP中文网 2017-04-17 15:27:32
0
3
595
#include <iostream>
#include <iterator>

int main()
{
    int a, b;
    int *c = &a, *d = &b;
    std::cout << std::hex << c << " " << d << std::endl;
    std::cout << std::hex << std::distance(d, c) << std::endl;
    return 0;
}

我运行时显示
c和d的值是00FDF7EC 00FDF7E0
std::distance(d, c)求出的值是3
可是他们地址相差不是C么,为什么是3?

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(3)
刘奇

std::distance returns the distance of the iterator, not the difference in addresses.
For example, you can also use std::distance(list::begin(),list::end()) to calculate the number of ++ between two iterators in the linked list, and we know that the addresses of the linked list are not in order Emissions.
The pointer c above also reaches the position of d after ++ three times. The ++ of int* moves sizeof(int) every time.
Generally speaking, the implementation of distance is to ++ move the iterator in the for loop and then compare to record the distance between them.

大家讲道理

std::distance returns not the number of bytes between d and c, but the number of ds between c and 元素. The 元素 here refers to The type c to which d and int belong.

Because int is of size 4 bytes, so 元素个数 = (C - 0) / 4 = 3

大家讲道理
c和d的值是00FDF7EC 00FDF7E0

c is the pointer to a, at the high address on the stack

d is the pointer to b, at the low address on the stack

The difference between c and d is 12 bytes, and 12 bytes are the bytes occupied by the size of 3 int types

std::distance(d, c)求出的值是3

sizeof(int) 为 4

12 / 4  = 3

So the distance between c and d is 3 int type size bytes

The distance the pointer moves in addition and subtraction is the size of the type pointed by the pointer

The pointer addition and subtraction in this problem results in the number of ints (four bytes), and pointers do not perform bit operations

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!