结构取代了自身价值的数组 [英] Array of structs replacing values over itself
问题描述
好了,所以我有低于code和我只是从文件中提取的各种事物和结构的数组输入查询他们来说,这貌似的作品开始,但是当我去打印出来它完成后,与文件似乎已经取代了所有的课程和名称与最后谷,奇怪的是,这并不与整数(级)发生,成绩也得到适当的inputed。
Ok so I have the below code and I am just pulling various things from a file and inputing them in an array of structs, it "seemingly" works initially, BUT when I go to printing it after it is done with the file it seemed to have replaced all of the courses and names with the very last vale, oddly this doesnt happen with the integers (grades), the grades do get inputed properly.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student {
char *name;
char *course;
int grade;
};
void courseSort(struct student d[20], int size);
int main(void)
{
FILE* fp;
char* filename = "grades.csv";
char buffer[100];
char* name, *class;
char* del=",";
int grade, i, counter=0;
struct student d[20];
if((fp=fopen(filename, "r"))==NULL)
{
printf("unable to open %s\n", filename);
exit(1);
}
while(fgets(buffer, sizeof(buffer), fp) !=NULL)
{
name = strtok(buffer,del);
class=strtok(NULL,del);
grade = atoi(strtok(NULL,del));
d[counter].name=name;
d[counter].course=class;
d[counter].grade=grade;
printf("%s %s %d\n",d[counter].name,d[counter].course,d[counter].grade);
counter++;
}
printf("\n\n\n");
for(i=0;i<counter;i++)
printf("%s %s %d\n",d[i].name,d[i].course,d[i].grade);
courseSort(d,counter);
fclose(fp);
}
我不知道我在做什么错:(这一切似乎简单,但不知道为什么它只是替换了最新一期的一切。
I am not sure what I am doing wrong :( it all seems straightforward but not sure why it just replaces everything with the latest one.
推荐答案
的 strtok的
返回一个指针到缓冲区,并没有分配内存。既然你不复制的字符串,最终有很多指向一个是在每次循环覆盖相同的缓冲区指针。
The strtok
returns a pointer to the buffer and does not allocate memory. Since you do not copy the strings, you end up with lots of pointers pointing to the same buffer that is overwritten at each iteration of the loop.
要解决这个问题,你需要改变你的循环使用复制的字符串的strdup
:
To fix this, you need to change your loop to copy the strings using strdup
:
while(fgets(buffer, sizeof(buffer), fp) != NULL)
{
d[counter].name = strdup(strtok(buffer, del));
d[counter].course = strdup(strtok(NULL, del));
d[counter].grade = atoi(strtok(NULL, del));
counter++;
}
不要忘了返回与免费
已分配的内存一旦你不再需要该字符串:
Don't forget to return the allocated memory with free
once you no longer need the strings:
for (i = 0; i < counter; i++) {
free(d[i].name);
free(d[i].course);
d[i].name = NULL;
d[i].course = NULL;
}
注意的strdup
是POSIX1.2001标准,而不是C89的一部分的一部分。如果没有,你必须自己重新实现它(很容易):
Note that strdup
is part of POSIX1.2001 standard, not part of C89. If it is not available, you'll have to re-implement it yourself (quite easy):
char *my_strdup(const char *str) {
char *copy;
size_t len = strlen(str) + 1;
if (len == 0) return NULL;
copy = (char *)malloc(len);
if (copy == NULL) return NULL;
memcpy(copy, str, len);
return copy;
}
这篇关于结构取代了自身价值的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!