如何将指针分配给结构内的指针?

时间:2021-04-18 04:46:38

标签: c

如何将指针分配给结构中的指针?

struct student{
    char name[24];
    int age;
    int height;
    int weight;
}

struct aClass{
    struct student *students;
    int rowsUsed;
}

void addTo(struct aClass *db, struct student *a){
    ...
}

如何将指针分配给结构中的另一个指针?

我试过了

db -> students[db -> rowsUsed] = *a;
db -> rowsUsed = db -> rowsUsed + 1;

但它不起作用。

1 个答案:

答案 0 :(得分:2)

检查类型...

db -> students[db -> rowsUsed] = a;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^   ^
   Type is "struct student"      Type is "pointer to struct student"

因此,您正在尝试在类型不兼容的对象之间进行分配。那会失败。您需要在运算符的两侧使用相同的类型。

也许你想要

db -> students[db -> rowsUsed] = *a;
                                 ^^
                                 Now it's the struct student that a points to