在结构中的数组内的结构中访问(使用指针)变量的正确方法是什么?
我想用function()
的指针到达position2D中的变量x和y?请注意,我遍历函数()中的节点(和点),并希望编写如下内容:
draw_point(p->vertices[i]->x, p->vertices[i]->y);
但这似乎不起作用。
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?
}
}
答案 0 :(得分:1)
vertices
是一个普通的结构变量,而不是 struct pointer 类型。在访问x
和y
时,请使用点.
运算符代替->
运算符
替换以下声明
draw_point(p->vertices[i]->x, p->vertices[i]->y);
与
draw_point(p->vertices[i].x, p->vertices[i].y);
编辑:分配next
字段时代码中的另一个问题。
node node1 = {1, {{0,0}, {5,0}, {5,5}, {0,5}}, &next1};
应该是
node node1 = {1, {{0,0}, {5,0}, {5,5}, {0,5}}, (struct Node*)next1};
这是工作代码
#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;
}