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",int((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 (also added safety to prevent the function being called with an unrelated pointer):
#include <stdio.h>
#include <assert.h>
char A[100][100];
void func(void *ptr)
{
char *ptrc = (char*)ptr;
ptrdiff_t diff = (ptrc-A[0]);
assert(0 <= diff);
assert(diff < sizeof(A));
printf("index %d %d\n",(int)(diff/sizeof(A[0])),(int)(diff % sizeof(A[0])));
}
int main()
{
char *ptr = &(A[5][34]);
func(ptr);
}
result:
index 5 34