简体   繁体   English

访问结构内数组中的结构

[英]Accessing a struct within array within a struct

What's the correct way of accessing (with a pointer) a variable within a struct within an array within a struct? 访问(使用指针)结构内数组中的结构内变量的正确方法是什么?

I's like to get to variables x and y within position2D with a pointer from function() ? 我想使用function()的指针访问position2D中的变量x和y? Note that I'm traversing the nodes (and the points) in function(), and was hoping to write something like: 请注意,我正在遍历function()中的节点(和点),并希望编写如下内容:

draw_point(p->vertices[i]->x, p->vertices[i]->y);

but that doesn't seem to work. 但这似乎不起作用。

typedef struct Position2D{
  uint8_t x;
  uint8_t y;
} position2D;

typedef struct Node{
  int num;
  position2D vertices[4];
  struct Node *next;
} node;

/* initialisation: */

node *next1 = NULL; //should be empty
node node1 = {1, {{0,0}, {5,0}, {5,5}, {0,5}}, &next1};
node *next0 = &node1;
node node0 = {0, {{0,10}, {10,10}, {10,15}, {0,15}}, &next0};
node *start = &node0;

/*traverse all nodes and their inner vertices arrays: */
void function(void){
node *p;
for(p = start; p != NULL; p = p->next){
  int i;
  for (i=0; i<4; i++){ //traverse their four points
    //How to get to the x and y at this line?
  }
}

vertices is a normal structure variable, not of struct pointer type. vertices是正常的结构变量,而不是结构指针类型。 While accessing x and y use dot . 访问xy使用dot . operator instead of -> operator 运算符,而不是->运算符

Replace below statement 替换下面的语句

draw_point(p->vertices[i]->x, p->vertices[i]->y);

with

 draw_point(p->vertices[i].x, p->vertices[i].y);

EDIT : Another problem in your code while assigning next field. 编辑:分配next字段时代码中的另一个问题。

node node1 = {1, {{0,0}, {5,0}, {5,5}, {0,5}}, &next1};

should be 应该

node node1 = {1, {{0,0}, {5,0}, {5,5}, {0,5}}, (struct Node*)next1};

Here is the working code 这是工作代码

#include<stdio.h>
typedef struct Position2D{
        int x;
        int y;
} position2D;

typedef struct Node{
        int num;
        position2D vertices[4];
        struct Node *next;
} node;
/*traverse all nodes and their inner vertices arrays: */
void function(void){
/* initialisation: */
        node *next1 = NULL;
        node node1 = {1, {{0,0}, {5,0}, {5,5}, {0,5}}, (struct Node*)next1};
        node *next0 = &node1;
        node node0 = {0, {{0,10}, {10,10}, {10,15}, {0,15}}, (struct Node*)next0};
        node *start = &node0;
        node *p = NULL ;
        int i=0;
        for(p=start;p!=NULL;p=p->next) {
                for (i=0; i<4; i++){ //traverse their four points
                        printf("%d %d \n",p->vertices[i].x, p->vertices[i].y);
                }
        }

}
int main() {
        function();
        return 0;
}

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

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