Bob Bob - 1 month ago 7
C Question

Index of element pointed to by pointer

I have a 2D char array declared as

char A[100][100]


I also have a pointer that points to one element of that array

char *ptr;
ptr = A[5]


This pointer gets passed to another function, which needs to be able to know the index of that pointer (in this case, 5)

void func(void *ptr) {
int index = ???
}


How can I do this? Is this even possible?

Answer

Yes it is possible if you can see A in func (A is just a doubly-indexed 1D array, not a pointer on arrays, that's why it is possible).

#include <stdio.h>

char A[100][100];

void func(void *ptr) {
  char *ptrc = (char*)ptr;
  printf("index %d\n",(ptrc-A[0])/sizeof(A[0]));
}

int main()
{
  char *ptr = A[5];
  func(ptr);
}

result:

index 5

of course, if you pass an unrelated pointer to func you'll have undefined results.

Note: it is required to cast the incoming void * pointer to char * or the compiler won't let us diff pointers of incompatible types.

EDIT: as I was challenged by chqrlie to compute both indexes, I tried it and it worked:

#include <stdio.h>

char A[100][100];

void func(void *ptr) {
  char *ptrc = (char*)ptr;
  int diff = (ptrc-A[0]);
  printf("index %d %d\n",diff/sizeof(A[0]),diff % sizeof(A[0]));
}

int main()
{
char *ptr = &(A[5][34]);
func(ptr);
}

result:

index 5 34