[英]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.