C-指向指针的索引 [英] C - index on pointer to pointer
问题描述
如果我有
struct X {
int a;
struct X* next;
}
struct X** ptr;
ptr初始化为结构X的地址,每个结构X的 接下来指向另一个结构X.使用
ptr is initialized with the address of a struct X, and each struct X 's next points to another struct X. What will one get by using
ptr[i] // where i is unsigned int
以下是我问题的来源 :(它是来自selinux的代码的链接):
Here is the source of my question : (it's link to code from selinux) : code
这些类型在以下类型中定义:类型
The types are defined in : types
推荐答案
您将获得垃圾.为了使p[i]
中的指针算法起作用,您需要在内存中(在数组中)一个接一个地放置对象(在这种情况下,指向结构的指针).
You will get garbage. For the pointer arithmetic in p[i]
to work you need to have the objects (in this case the pointers-to-struct) one after the other in the memory (in an array).
根据您的情况,您需要遵循next
指针i
次.
In your case you need to follow the next
pointer i
times.
struct X *p = *ptr;
for (j = 0; j < i; ++j) p = p->next;
/* now p points to the i-th struct */
如果结构实际上在数组中,则等效于
If the structs are in fact in an array, this is equivalent to
struct X *p = (*ptr)[i];
但是在那种情况下,next
将毫无用处.
But in that case, the next
would be useless.
这篇关于C-指向指针的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!