在malloc C之后写入数组的问题
在使用malloc函数分配内存后,我在尝试写入结构的数组位置时遇到了一些问题。我必须从file.txt(行的格式:int string char)中读取一些数据。这些数据是一个人的id、一个非特定的字符串和一个给出要读取和保存的字符串“类型”的字符)、每行数据以及保存在struct数组中的数据。不幸的是,我经常不得不向结构数组中的上一个索引添加数据,但程序似乎不允许我写入结构数组的上一个索引。我不知道为什么。 希望我说得够清楚。谢谢你的帮助 下面是file.txt的一个示例:在malloc C之后写入数组的问题,c,arrays,struct,malloc,C,Arrays,Struct,Malloc,在使用malloc函数分配内存后,我在尝试写入结构的数组位置时遇到了一些问题。我必须从file.txt(行的格式:int string char)中读取一些数据。这些数据是一个人的id、一个非特定的字符串和一个给出要读取和保存的字符串“类型”的字符)、每行数据以及保存在struct数组中的数据。不幸的是,我经常不得不向结构数组中的上一个索引添加数据,但程序似乎不允许我写入结构数组的上一个索引。我不知道为什么。 希望我说得够清楚。谢谢你的帮助 下面是file.txt的一个示例: 6
6 //number of lines
3 tPar P
2 tPar P
3 tArr A
1 tPar P
1 tArr A
2 tArr A
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define DBG printf("Ok linea %d\n", __LINE__);
typedef enum {
false,
true
} bool;
struct file {
char name[15];
int n;
struct record *rec;
};
struct record {
int cod;
char tPar[10];
char tArr[10];
};
int read(struct file *f) {
FILE *fd;
char str[100];
int pCod;
char pTime[10];
char pChar;
bool found;
int i = 0;
int j;
fd = fopen(f->name, "r");
if(!fd) {
printf("Errore di apertura file.\n");
exit(1);
}
fscanf(fd, "%d\n", &f->n);
f->rec = malloc((f->n)*sizeof(struct record));
if(f->rec == NULL) {
printf("Errore nell'allocazione della memoria.\n");
exit(1);
}
while(fgets(str, 100, fd)) {
sscanf(str, "%d %s %c", &pCod, pTime, &pChar);
pChar = toupper(pChar);
found = false;
f->rec[i].cod = 0; // these 4 lines are needed just
strcpy(f->rec[i].tPar, "xxx"); // to check if it writes in the
strcpy(f->rec[i].tArr, "xxx"); // struct array
for(j=0; j<i; j++) {
if((pCod == f->rec[j].cod) && (pChar == 'P')) {
strcpy(f->rec[j].tPar, pTime); // doesn't copy
found = true;
}
if((pCod == f->rec[j].cod) && (pChar == 'A')) {
strcpy(f->rec[j].tArr, pTime); // doesn't copy
found = true;
}
}
if(!found) {
f->rec[i].cod = pCod;
if(pChar == 'P')
strcpy(f->rec[i].tPar, pTime);
if(pChar == 'A')
strcpy(f->rec[i].tArr, pTime);
}
if(pChar == 'P')
printf("%d %s %c\n", f->rec[i].cod, f->rec[i].tPar, pChar);
if(pChar == 'A')
printf("%d %s %c\n", f->rec[i].cod, f->rec[i].tArr, pChar);
i++;
}
fclose(fd);
return 0;
}
int main(int argc, char *argv[]) {
struct file f;
strcpy(f.name, argv[1]);
read(&f);
return 0;
}
实际产量:
3 tPar P
2 tPar P
0 xxx A
1 tPar P
0 xxx A
0 xxx A
我怀疑bool的枚举值没有编译为0和1,因此您的测试
if(!found) {
它看起来不起作用。(不过,我现在无法真正验证我的理论)。不要键入def
bool
。而是包含#!你为什么要使用i++?如果只在(!found)中执行此操作,则可能会在for中遇到分段错误(f=0…用于循环。看起来我是用来跟踪记录的数量,而不是你读过的行数。@chux,是的,现在我明白你的意思了。我添加了逗号只是为了让你明白,它不在原始的.txt中。仍然使用i++;
在if(!found)之外{
还是你像@JustinDanielson建议的那样把它放在那里了?在更正之前,代码将失败。好的,各位!它工作了!对不起,@MattMcNabb,我真的认为malloc是问题所在。谢谢你们,伙计们!我感谢你们的帮助!如果我检查了,我的bool工作正常,问题就不会那么严重了。enum
sd第一个是0
,后续的1
比前一个大(除非指定了具体的值)@Matt,Doh!是的,你说得很对。当我记不起它是否从1开始时,我去查阅了它。
if(!found) {