c - 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
,程序运行良好。我很困惑是否需要使用->
. 我希望结构向量不使用堆栈内存,而是使用堆。
解决方案
为了直接访问 struct 的成员,您需要使用.
. 要使用指针访问,您需要使用->
. 在您的代码中,list
是一个结构指针,但list[i]
它是一个结构。这就是为什么您无法通过->
.
推荐阅读
- json - 使用rest api与本地工具查询时OPA中的不同输入格式
- typescript - 使用 preloadedState 时生成 Redux Toolkit TypeScript 类型
- sql - 如果当前月份没有数据,则获取上个月的数据
- javascript - 如何将消息过滤器添加到来自 SES 的 SNS 消息发布
- python - 2个numpy数组之间的随机插值
- android - Flutter - WhatsApp 状态保护程序在 android 10 或更高版本中不工作
- java - JUnit 测试在 Eclipse 中运行良好,但不适用于“build gradle”命令。它因依赖错误而失败
- java - 为什么我在 Mac 上看到“java.lang.reflect.InaccessibleObjectException:无法使私有 java.nio.DirectByteBuffer(long,int) 可访问”
- angular - 获取在 html 中定义的 Dart 组件的实例
- python - 如何突出显示除 NaN 之外的所有重复行?