首页 > 解决方案 > 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");
    }
}   

编译器说

错误:'->' 的类型参数无效(有 'Person')

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

标签: cstructmalloctypedef

解决方案


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


推荐阅读