繁体   English   中英

C-结构数组取消引用中的双指针结构

[英]C - Double Pointer Struct inside a Struct Array Dereference

我在尝试取消对结构数组的双指针引用时遇到麻烦。

该结构定义:

struct node_list_t {
     struct node_t **node_ptr;
};

我已经做了以下分配内存和初始化值的操作:

struct node_t *nodeArray;
struct node_list_t *mainList = (struct node_list_t*)malloc(sizeof(struct node_list_t));

nodeArray =(struct node_t*)malloc(10 * sizeof(struct node_t));
for (i=0;i<size;i++) {
    nodeArray[i].mass = i;
}

mainList->node_ptr = &nodeArray;

由于我们被要求使用双指针,因此我尝试以下操作未能成功取消引用:

printf("%f\n",mainList->node_ptr[i]->mass);

我们被迫将node_ptr保留为双指针,因此我无法更改它。 我将如何取消引用? 谢谢。

好吧,那将是

printf("%f\n",(*mainList->node_ptr)[i].mass);

为什么? mainList->node_ptr是指向struct node_t双指针。

*mainList->node_ptr取消引用双指针,您将获得一个指向struct node_t的指针:从第二个malloc返回的指针。

因此(*mainList->node_ptr)[i].mass等效于

struct node_t *nodes = *mainList->node_ptr;
// nodes[0] is the first node, nodes[1] the second, etc.
nodes[i].mass;

编辑

当您在一行中找不到正确的取消引用时,请按照上面的示例逐步进行操作。 然后,将其重写为一行要容易得多。

编辑2

由于OP从问题中删除了代码,因此没有这个答案就没有意义,这是原始代码:

 struct node_list_t { struct node_t **node_ptr; }; 

我已经做了以下分配内存和初始化值的操作:

 struct node_t *nodeArray; struct node_list_t *mainList = (struct node_list_t*)malloc(sizeof(struct node_list_t)); nodeArray =(struct node_t*)malloc(10 * sizeof(struct node_t)); for (i=0;i<size;i++) { nodeArray[i].mass = i; } mainList->node_ptr = &nodeArray; 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM