簡體   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