【发布时间】:2021-12-25 02:29:36
【问题描述】:
好的,我正在尝试将文本文件中的数据输入到字符串的动态数组中。每个数据元组有 6 个属性。因此有 6 个数组。问题是当我填充所有数组时,它会在循环中打印正确的值。 但是当我尝试访问循环外的任何数组元素时,它会给出文本文件的最后一个单词作为输出。我已经尝试了所有可用的解决方案,但似乎都不起作用。
代码是:
int n(FILE **fp, int size, char **presenters, char **birth_numbers, char **room_codes,
char **authors, char **post_titles, char **presentation_types, char **presentation_times,
char **dates){
// Buffer to get input from the file.
char buffer[200];
// To check if the file is open or not
if (*fp == NULL){
printf("File not Open");
}
else{
char *file = "konferencny_zoznam.txt";
fseek(*fp, 0, SEEK_SET);
if (size >= 1){
int length_of_arrays = sizeof presenters / sizeof *presenters;
if (length_of_arrays > 1){
printf("in null if");
free(presenters);
free(birth_numbers);
free(room_codes);
free(authors);
free(post_titles);
free(presentation_times);
free(presentation_types);
free(dates);
}
presenters = malloc((size+1)* sizeof(char*));
birth_numbers = malloc((size+1)* sizeof(char*));
room_codes = malloc((size+1)* sizeof(char*));
authors = malloc((size+1)* sizeof(char*));
post_titles = malloc((size+1)* sizeof(char*));
presentation_times = malloc((size+1)* sizeof(char*));
presentation_types = malloc((size+1)* sizeof(char*));
dates = malloc((size+1)* sizeof(char*));
const unsigned MAX_BUFFER_LENGTH = 256;
char buffer[MAX_BUFFER_LENGTH];
int i = 0, len = 0;
while(fgets(buffer, MAX_BUFFER_LENGTH, *fp)){
// len = strlen(buffer)+1;
presenters[i] = buffer;
fgets(buffer, MAX_BUFFER_LENGTH, *fp);
birth_numbers[i] = buffer;
fgets(buffer, MAX_BUFFER_LENGTH, *fp);
room_codes[i] = buffer;
fgets(buffer, MAX_BUFFER_LENGTH, *fp);
authors[i] = buffer;
fgets(buffer, MAX_BUFFER_LENGTH, *fp);
post_titles[i] = buffer;
fgets(buffer, MAX_BUFFER_LENGTH, *fp);
presentation_times[i] = buffer;
fgets(buffer, MAX_BUFFER_LENGTH, *fp);
presentation_types[i] = buffer;
fgets(buffer, MAX_BUFFER_LENGTH, *fp);
dates[i] = buffer;
printf("buffer : %s", dates[i]);
fgets(buffer, MAX_BUFFER_LENGTH, *fp);
i++;
}
for (int i=0; i<8; i++){
printf("presenter[0]: %s", dates[i]);
// Outputs 20200406 for each iteration which is the last word of file.
}
}
else {
printf("File not read already. Consider running command v before.");
}
}
}
【问题讨论】:
-
此声明 int length_of_arrays = sizeof presenters / sizeof *presenters;没有意义。相当于 int length_of_arrays = sizeof( char ** ) / sizeof( char * ) ;
-
每当你分配一个元素时,你就是在分配一个指向函数
buffer数组的指针的副本。结果,所有数组的所有元素都指向同一个存储,其内容就是最后存储在那里的内容。更重要的是,当if (size >= 1)块的执行终止时,该对象的生命周期结束,这些指针全部悬空。您需要动态分配buffer的副本,并为其分配指针。 -
提示:改为使用结构数组以使其更具可读性。
-
@AndersK 规则是不要以任何方式使用 struct。
-
你没有提到你的分配参数
标签: c malloc dynamic-memory-allocation dynamic-arrays pass-by-value