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;
};
I have done the following to allocate memory and initialize values:
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;
我在尝试取消引用指向结构数组的双指针时遇到问题。
结构已定义:
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; };
I have done the following to allocate memory and initialize values:
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;