4

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?

Bob
  • 715
  • 2
  • 11
  • 32

2 Answers2

3

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
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
2

You can compute the offset of ptr from the beginning of the array and derive the coordinates:

#include <stdio.h>
#include <stdlib.h>

char A[100][100];

void func(void *ptr) {
    if (ptr == NULL) {
        printf("ptr = NULL\n");
        return;
    }
    ptrdiff_t pos = (char *)ptr - A[0];
    if (pos < 0 || pos > (ptrdiff_t)sizeof(A)) {
        printf("ptr points outside A: ptr=%p, A=%p..%p\n",
               ptr, (void*)A, (void*)&A[100][100]);
    } else {
        printf("ptr = &A[%d][%d]\n",
               (int)((size_t)pos / sizeof(A[0])),  // row number
               (int)((size_t)pos % sizeof(A[0])))  // column number
    }
}

int main(void) {
    char *ptr = &A[5][3];
    func(ptr);
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • For this `size_t pos` there is `ptrdiff_t`. – alk Oct 30 '16 at 09:59
  • @alk: That's correct, but `pos` is positive by constuction if `ptr` is a valid pointer inside `A` or at its upper edge. The conversion is fine in this case. If `ptr` is `NULL` or points outside `A`, computing the difference is meaningless anyway. – chqrlie Oct 30 '16 at 11:14