C 当一个结构的属性是指向另一个结构的指针时

C 当一个结构的属性是指向另一个结构的指针时,c,arrays,pointers,struct,C,Arrays,Pointers,Struct,(使用C) 如果我想调用一个结构的给定属性,我只需要使用符号struct.attribute。但是,有时所讨论的属性是指向另一个结构的指针。在本例中,我将使用struct.pointer\u to\u struct。 那么,如何调用指向的结构的属性呢?写入:struct.pointer\u to\u struct->attribute似乎合乎逻辑,但编译器不接受这一点。 下面是一个例子: #include <stdio.h> #include <stdlib.h> #in

(使用C) 如果我想调用一个结构的给定属性,我只需要使用符号struct.attribute。但是,有时所讨论的属性是指向另一个结构的指针。在本例中,我将使用struct.pointer\u to\u struct。 那么,如何调用指向的结构的属性呢?写入:struct.pointer\u to\u struct->attribute似乎合乎逻辑,但编译器不接受这一点。 下面是一个例子:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct thing
{
        char gender[6];
        char name[21];
        struct thing **friends;
};

int main(void)
{
        struct thing things[3];

        strncpy(things[0].name, "Bob", 21);
        strncpy(things[1].name, "Kelly", 21);
        strncpy(things[1].gender, "Female", 6);

        things[0].friends = &things[1];

        printf("%s is friends with %s\n", things[0].name, things[0].friends->name);

        return 0;
}
#包括
#包括
#包括
结构物
{
性别[6];
字符名[21];
结构物**朋友;
};
内部主(空)
{
结构物[3];
strncpy(things[0]。名称,“Bob”,21);
strncpy(things[1]),名字“Kelly”,21岁;
strncpy(事物[1]。性别,“女性”,6);
事物[0]。朋友=&事物[1];
printf(“%s是%s的朋友\n”,事物[0]。名称,事物[0]。朋友->名称);
返回0;
}
行printf(“%s是%s的朋友,\n”,事物[0]。名称,事物[0]。朋友->名称);由于[0]的原因,无法编译。朋友->名称。 我想找到一种说‘Bob是Kelly的朋友’的方式,当只针对Bob编写代码时

struct thing
{
        char gender[6];
        char name[21];
        struct thing **friends; // why thing **
};
应该是,

struct thing*friends
而非
struct thing**friends

这不是“指向结构的指针”,而是“指向结构指针的指针”,也称为“指向结构指针数组的指针”:

因此,您需要打印

things[0].friends[0]->name
对于第一个朋友,
friends[1]->name
对于第二个朋友,依此类推

(但由于您没有任何“number of friends”整数变量,因此可能很难使用该变量。此外,您以错误的方式填充了该变量,因此需要创建一个额外的数组,其中包含指向某个位置(例如堆上)的朋友的各个指针。)

things[0].friends[0]->name