gpt4 book ai didi

c - 应用malloc

转载 作者:行者123 更新时间:2023-11-30 18:43:40 26 4
gpt4 key购买 nike

伙计们...你能帮我在我的代码中应用 malloc...这是我的代码:

#include<stdio.h>
#include<stdlib.h>
struct studentinfo{
char id[8];
char name[30];
char course[5];
}s1;
main(){
int i;
FILE *stream = NULL;
stream = fopen("studentinfo.txt", "a+");

struct studentinfo s1;
struct studentinfo array[3];
for (i =0; i<1; i++){
printf("Enter Student ID: ");
scanf("%s", s1.id);
fflush(stdin);
printf("Enter Student Name: ");
gets(s1.name);
fflush(stdin);
printf("Enter Student Course: ");
scanf("%s", s1.course);

fprintf(stream, "\n%s,\t%s,\t%s", s1.id, s1.name, s1.course);
}
fclose(stream);
getch();
}

我知道 malloc 比通常的数组分配更多的空间...但我仍然很难使用它...非常感谢:)

最佳答案

#include<stdio.h>
#include<stdlib.h>
struct studentinfo{
char id[8];
char name[30];
char course[5];
};
main(){
int i;
FILE *stream = NULL;
stream = fopen("studentinfo.txt", "a+");

struct studentinfo * s1 = (struct studentinfo *)malloc(sizeof(struct studentinfo));

struct studentinfo * array = (struct studentinfo *)malloc(sizeof(struct studentinfo) * 3);
for (i =0; i<1; i++){
printf("Enter Student ID: ");
scanf("%s", s1->id);
fflush(stdin);
printf("Enter Student Name: ");
gets(s1->name);
fflush(stdin);
printf("Enter Student Course: ");
scanf("%s", s1->course);

fprintf(stream, "\n%s,\t%s,\t%s", s1->id, s1->name, s1->course);
}
fclose(stream);
getch();
}

顺便说一句:
- fflush(stdin) 不可移植。
- gets() 很危险,用 fgets() 替换它

关于c - 应用malloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4345916/

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