gpt4 book ai didi

C,为结构数组内的字符串分配内存

转载 作者:行者123 更新时间:2023-11-30 17:00:59 25 4
gpt4 key购买 nike

我已经在这个网站上充分了解了这个问题,但仍然没有找到解决方案。我有一个结构数组,我想从文件中读取一些记录并将它们存储在结构中。问题在于内存的分配。这是我使用的结构:

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,我必须修改它才能读取记录。

最佳答案

两者之间有很大区别:

(*data)[i].nome = malloc(sizeof(char) * MAX_LENGTH + 1);

和:

(*data)[i]->cognome = malloc((sizeof(char) * MAX_LENGTH + 1));

使用点符号的第一行表示访问 struct 的成员,而 -> 表示使用指针访问 struct 的成员符号,即指向结构的指针。

这里出现了困惑,因为 (*data) 是一个指向 Record 类型的结构的指针,它是 Rec 的类型定义>。

typedef struct Rec* Record; 

由于 data 被剥离后,是 Record 的类型定义,别名为指向 Rec 结构的指针。双指针作为参数的一部分,将通过引用传递进行修改,在确定输入数据集中的行数后,将其声明为指针数组:

*data = (Record*)malloc(n * sizeof(Record));

访问成员数据,对于数组中的每个条目将是:

(*data)[i] dot name_of_member

如果类型定义是这样的,规则就会改变:

typedef struct Rec Record;

即一个普通的结构体,没有指针的使用。

那么,如果分配成功,就可以访问成员(member)数据,

(*data)[i]->name_of_member

但是,不要尝试将指针隐藏在 typedef 后面,因为这会带来悲伤,将来再次回到代码,并想知道为什么会失败,隐藏指针咬住了你!

关于C,为结构数组内的字符串分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37272458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com