C 中“->”(结构的动态分配向量)的无效类型参数

Invalid type argument of '->' (Dynamic allocated vector of structs) in C

我知道在访问本地结构向量成员时使用 vector[i].member。但是我现在正在研究动态分配,据我所知,当结构 vector 是动态的时,我需要使用 -> 来访问成员。

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

//Struct that stores a person's number and first name. 
typedef struct person{
    int number;
    char* first_name;
} Person;

int main(){

    int List_size; //Stores the size of the list. 
    scanf("%d", &List_size);

    Person* list= (Person*) malloc(List_size * sizeof(Person));     //Allocate a vector of persons struct in a variable list. 

    for(int i = 0; i < List_size; i++){       //Fills each person of list   
        scanf("%d", &(list[i]->number)); 
        (list[i]->first_name) = (char*) malloc(100 * sizeof(char));
        scanf("%s",(list[i]->first_name));    
    }

    for(int i = 0; i < List_size; i++){       //Prints each person of list
        printf("%d is list[%d].number, and ", (list[i]->number), i);
        printf("%s is list[%d].name\n", (list[i]->first_name), i);
        printf("---------------\n");
    }
}   

编译器说

error: invalid type argument of '->' (have 'Person')

但是,当我使用 list[i].member 而不是 list[i]->member 时,程序运行得非常好。我很困惑是否需要使用 ->。我希望结构向量不使用堆栈内存,而是使用堆。

为了直接访问struct的成员,你需要使用.。要使用指针访问,需要使用->。在您的代码中,list 是一个结构指针,但 list[i] 是一个结构。这就是为什么您无法通过 ->.

访问的原因