gpt4 book ai didi

c - 为什么我的 C 代码不能使用指针和结构体工作?

转载 作者:行者123 更新时间:2023-11-30 16:44:50 25 4
gpt4 key购买 nike

为什么不起作用?存在地址访问错误。但是,我尝试通过互联网和谷歌找到问题所在,但找不到。我正在做我的作业。我的助手要求我们使用

STUDENT ** list  and Malloc ()

但是他们没有完美地解释,所以我很困难。我怎么解决这个问题?为什么我会收到错误?

最佳答案

看来您需要使用STUDENT **list,尽管这不是完成这项工作的最佳方式。但鉴于这是一个练习,我会坚持下去,并且 STUDENT **list 将是指向该 struct 的指针数组。

你的程序有两个主要错误。

  • 不为指针数组的每个元素分配内存
  • 将输入数据分配给本地结构,该结构被遗忘函数退出。

当您尝试打印数据时,这两个中的第一个是致命的,因为您使用了未初始化的指针。

还有其他一些事情您应该经常检查

  • malloc返回的值
  • scanf 函数的结果(scanf返回的值)

此外,您必须

  • 限制字符串输入溢出
  • 使用后释放内存

这是代码的基本修复,仍然需要提到的其他改进。

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

#define ID_LEN 7
#define NAME_LEN 10

typedef struct{
char id[ID_LEN];
char name[NAME_LEN];
int math;
int eng;
} STUDENT;

void SHOW(STUDENT* list) {
printf("ID : %s\n", list->id);
printf("name : %s\n", list->name);
printf("math : %d\n", list->math);
printf("eng : %d\n", list->eng);
}

void FirstList(STUDENT *list){
printf("ID : ");
scanf("%s", list->id); // use the pointer passed
printf("Name : "); // instead of local struct
scanf("%s", list->name);
printf("Math score: ");
scanf("%d",&list->math);
printf("English score: ");
scanf("%d",&list->eng);
}

int main(){
STUDENT **list = NULL;
int num = 0;
printf("How many student? ");
scanf("%d", &num);
list = malloc(num * sizeof(STUDENT*));
for(int i=0; i<num; i++) {
list[i] = malloc(sizeof(STUDENT)); // allocate memory for struct
FirstList(list[i]);
}

for(int i=0; i<num; i++) {
SHOW(list[i]);
}
return 0;
}

关于c - 为什么我的 C 代码不能使用指针和结构体工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44352452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com