我正在从文件读入结构并遇到问题。我有测试文件,其中第一个字母定义结构名称,第二个数字告诉我它有多少个节点,其余数字是节点。文件示例:
A 4 1 2 3 4
B 5 1 2 3 9 8
C 3 1 2 3
例如结构应该是这样的:name->A;节点数->4;节点->{1,2,3,4}。我保存每一行的结构是这样的:
struct mystruct{
char name[1];
int numberOfNodes;
int nodes[];
};
到目前为止我的功能:
lines = lineCount(courses); //calculates how many rows file has
struct courses course[lines];
co = fopen(courses, mode);
if(co == NULL){
printf("Can't find the files.");
exit(1);
}else{
for(i = 0; i < lines; i++){
fscanf(co, "%1s %d \n", ¤t, &id1); //Doesnt have any problems reading these two parameters;
for(j = 0 ; j < id1; j++){
fscanf(co, "%d", &course[i].nodes[j]); //Have no idea how to store array =/
}
strcpy(course[i].courseName, current);
course[i].numberOfNodes = id1;
}
}
编辑:很抱歉让你们感到困惑,它分配整数很好,但不是输出相同的内容,而是输出如下内容:
A 4 69 72 1 2
B 5 20 45 7 3 1
C 3 2 45 1
我认为这段代码没有达到我想要的效果:
for(j = 0 ; j < id1; j++){
fscanf(co, "%d", &course[i].nodes[j]); //Have no idea how to store array =/
}
非常感谢任何帮助!
最佳答案
您的代码不会为整数数组分配任何内存,int Nodes[]
被称为灵活数组成员,它有其用途,并且它本身不保留任何内存,您需要为nodes
数组分配动态内存:
struct mystruct {
char name[1];
int numberOfNodes;
int *nodes;
};
...
fscanf(co, "%c %d \n", ¤t, &id1);
course[i].nodes = malloc(sizeof(int)*id1);
请注意,%1s
格式说明符扫描 1 个字符的字符串,它会在后面添加一个空终止字节,因此您应该使用 %c
来读取一个字符。
注意1:完成后不要忘记free()
所有已分配的内存,例如
free(course[i].nodes);
注2:C 中分配内存的惯用方法是:
malloc(num_of_elements * sizeof *ptr_to_type);
为了避免混淆,我没有在这里介绍这一点,另请注意,我个人不喜欢强制转换 malloc()
的结果,有一些很好的原因:
Do I cast the result of malloc?
关于c - 将文件中的整数数组存储在结构 C 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13835904/