The pointer of the item that the pointer points to.

I have a 2D char array declared as

char A[100][100]

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

char *ptr;
ptr = A[5]

This pointer is passed to another function that needs to know the index of this pointer (in this case 5)

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

How can i do this? Is it possible?

+4
source share
2 answers

Yes, perhaps, if you can see Ain func(A is just a 1D double-indexed array, not a pointer to arrays, then why is this 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 unbound pointer to func, you will get undefined results.

: void * char * .

EDIT: chqrlie , , ( , ):

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

:

index 5 34
+3

ptr :

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

Source: https://habr.com/ru/post/1659295/


All Articles