我已经在这个网站上看到了足够的关于这个问题,但仍然没有找到解决方案。 我有一个结构数组,我想从文件中读取一些记录并将它们存储在结构中。问题是内存的分配。 这是结构使用:C,为结构数组中的字符串分配内存
struct Rec{
int mat;
char *nome;
char *cognome;
};
typedef struct Rec* Record;
这是readFromFile功能:
void readFromFile(char* fileName, Record** data, int* pn)
{
char line[LINE_LENGTH];
int n, i;
char* token;
printf("\n\nReading file %s\n", fileName);
FILE* fin = fopen(fileName, "r");
if (fin == NULL)
{ printf("Error readinf file\n");getch();
goto end;
}
n = 0; // first read to know the number of lines
while (fgets(line, LINE_LENGTH, fin) != NULL) n++;
n = (n < MAX_LENGTH ? n : MAX_LENGTH);
printf("N: %d\n", n);
*pn = n;
//Then I allocate the memory for the n lines I previously read
*data = (Record*)malloc(n * sizeof(Record));
if(*data == NULL){
printf("Problem allocating memory\n");
exit(0);
}
i = 0;
for(i = 0; i < n; i++){
(*data)[i].nome = malloc(sizeof(char) * MAX_LENGTH + 1);
if((*data)[i]->nome == NULL){
printf("Problem allocating memory\n");
exit(1);
}
//Here comes the problem, the allocation of the second string fails and the program exit
(*data)[i]->cognome = malloc((sizeof(char) * MAX_LENGTH + 1));
if((*data)[i]->cognome == NULL){
printf("Problem allocating memory\n");
exit(2);
}
}
rewind(fin);
n = 0;
while (fgets(line, LINE_LENGTH, fin) != NULL && n < MAX_LENGTH)
{
token = strtok(line, ";");
strcpy((*data)[n]->nome, token);
token = strtok(line, ";");
strcpy((*data)[n]->cognome, token);
token = strtok(line, ";");
(*data)[n]->mat = atoi(token);
n++;
}
fclose(fin);
end:return;
}
我试图修改该结构,在许多方面的代码,但还没有找到一个解决方案,我认为这可能是一个指针问题,但我无法弄清楚。 readFromFile函数是由教授提供的,用于从文件中读取int,并且我必须修改它以读取记录。
'记录**数据,'加起来三颗星。 (记录已经是可怕的typedeffed指针) – joop
你不应该隐藏'typedef'后面的指针。 – user694733
另请参见:https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – szczurcio