A weird interview question I had yesterday
Given a void *p
pointer, and a int a = 1;
how to dereference to any level pointers?
For example,
if input is 1, then you can get the data by *(int *)p
if input is 2, then you can get the data by **(int **)p
if input is 3, then you can get the data by ***(int ***)p
but what if the input is n
? how can you get the data by *xN(int *xN)p
?
I completely had no idea.
Not at all tested, but I think this recursive solution is approximately right:
int get_pointer(void* p, int n)
{
if (n==1) return *p;
return get_pointer((void*)(*(int*)p), n-1);
}
Something like this:
int dereference(void *p, int n) {
for (int i = 0; i < n; i++) {
p = *((void **) p);
}
return (int)p;
}
烦恼:您可以使用for循环或运行input
时间的递归函数,并在每次循环中取消对指针的引用一次,将结果传递给下一次迭代。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.