繁体   English   中英

从 c 或 c++ 中的指针差异获取数组索引

[英]Get array index from pointer difference in c or c++

我知道如何从指针中获取指针并添加索引。 但是,如果您只有一个指向数组开头的指针和一个指向一个元素元素的指针,是否可以获得数组的索引?

#include <iostream>
#include <array>

auto pointer_from_diff(auto *x, auto *y) -> auto {
   return // ? what here?
}

auto main() -> int {
    auto x = std::array{1, 2, 3, 4};

    auto *p = &x[2];

    std::cout << pointer_from_diff(x.data(), p) << std::endl;
}

因为有人似乎不喜欢在 c 中标记的问题,所以这里有一些实际的 c 代码,供那些不会说 c++ 的人使用。

#include <stdio.h>

int pointer_from_diff(int *x, int *y) {
   return ?;// ? what here?
}

int main() {
    int x[] = {1, 2, 3, 4};

    int *p = &x[2];

    int index = pointer_from_diff(x, p);

    printf("%d", pointer_from_diff(x, p));
}

注意:我将其标记为 c++/c,并不是因为我想使用 c,而是因为我猜测这两种语言的解决方案是相似的。 因此,可以在 c++ 中实施的 c 中的解决方案是可以接受的。

我还在 c++ 版本中过度/误用了auto ,这与问题无关。

&x[k]&x[0] + k相同。

因此, p - &x[0]&x[0] + 2 - &x[0] ,即2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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