[英]Index of element pointed to by pointer
I have a 2D char array declared as 我有一个声明为的2D char数组
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) 该指针被传递给另一个函数,该函数需要能够知道该指针的索引(在本例中为5)
void func(void *ptr) {
int index = ???
}
How can I do this? 我怎样才能做到这一点? Is this even possible?
这甚至可能吗?
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). 是的,你可以在
func
看到A
(A只是一个双重索引的1D数组,而不是数组上的指针,这就是为什么它可能)。
#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. 当然,如果你将一个不相关的指针传递给
func
你将得到未定义的结果。
Note: it is required to cast the incoming void *
pointer to char *
or the compiler won't let us diff pointers of incompatible types. 注意:需要将传入的
void *
指针强制转换为char *
否则编译器不会让我们区分不兼容类型的指针。
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): 编辑:因为我被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);
}
result: 结果:
index 5 34
You can compute the offset of ptr
from the beginning of the array and derive the coordinates: 您可以从数组的开头计算
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.