【发布时间】:2014-07-19 05:46:14
【问题描述】:
我需要帮助解决以下代码。使用 gcc 编译代码后,它可以像 ./compiledFile inputFile.txt 一样运行它应该读取 inputFile.txt,同时为每个变量动态分配内存,在这种情况下为 name 和 courseID,但我的代码不起作用。我最不了解且需要帮助的地方是分配内存,将数据插入结构并打印数据,如下面的示例。通过查看这段代码,您可以看出我是 c 和动态内存分配和结构的新手。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct people
{
char* name[10];
char* courseID[15];
int grade;
};
void printData(struct people student[], int count);
int main(int argc, char* argv[])
{
FILE *in_file;
char buffer[30];
char *token, *del=",";
int count=0;
struct people student[20];
if(( in_file = fopen(argv[1], "r")) == NULL)
{
printf("unable to open the file");
}
while (fgets(buffer, sizeof(buffer), in_file))
{
student = malloc(sizeof(struct people));
token = strtok(buffer, del);
strcpy(student[count].name, token);
count++;
}
fclose(in_file);
printData(student, count);
}
void printData(struct people student[], int count)
{
int i;
for(i=0; i<count; i++)
{
printf("%s", student[i].courseID);
if (strcmp((student[i].name, student[i].courseID) > 0))
{
printf("%s %s", student[i].name, student[i].grade)
}
}
}
data.txt 文件包含以下内容,以逗号分隔:
John,MATH 1324,90
David,SCI 1401,88
Omondi,MATH 1324,89
David,MATH 1324,90
打印出来后应该如下所示:
MATH 1324
John 90
Omondi 89
David 90
SCI 1401
David 88
【问题讨论】:
-
struct student? 'student = malloc(sizeof(struct student))' 你的意思是student = malloc(sizeof(struct people))? -
抱歉错字应该是 struct people
-
你用这句话弄丢了我:
if (strcmp((student[i].name, student[i].courseID) > 0))意图是什么? -
我试图比较学生是否有 courseID 以在 courseID 下打印它们,但我对如何实现它有点迷茫。
标签: c memory-management dynamic-memory-allocation