Home > Software design >  Get array index from pointer difference in c or c
Get array index from pointer difference in c or c

Time:12-03

I know how to get a pointer from a pointer and adding a index. But is it possible to get the index of a array if you only have a pointer to the array beginning and a pointer to one element element?

#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;
}

Because someone seem to not like the question being tagged in c, here is some actual c-code for those of you who does not speek 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));
}

Note: I marked this as c /c, not because I want to use c, but because my guess is that the solution is similar for both languages. A solution in c that is possible to implement in c is therefore acceptable.

I also over/missuse auto for the lols in the c version and that is unrelated to the question.

CodePudding user response:

&x[k] is the same as &x[0] k.

Thus, p - &x[0] is &x[0] 2 - &x[0], which is 2.

  •  Tags:  
  • c c
  • Related