c - 动态数组分配仅返回所有索引中的最后一个元素 C
问题描述
好的,所以我正在尝试将文本文件中的数据输入到字符串的动态数组中。每个数据元组有 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.");
}
}
}
解决方案
你不能做
array[i] = buffer;
因为缓冲区是一个 char 数组,并存储了 char 数组的地址。当您将其值分配给一个新变量时,您基本上是将其地址复制到一个新变量中。这就是为什么您的数组的每个索引都指向同一个数组,该数组包含文件中的最新值。
您需要通过 strcpy 或其他方式复制缓冲区变量的内容来执行深层复制。
推荐阅读
- android - Android Room 获取今天插入的所有时间
- python - Python 代码返回空白图。我该如何纠正这个错误?
- encryption - 使用 SHA-256 的 RSA OAEP 加密失败,而使用 SHA-1 则正常
- database - 如何使用 docker 部署和配置远程 clickhouse db 实例
- css - 使用滚动 CSS 在一行中显示项目
- mysql - 将计算的 AVG 集成到同一查询中
- javascript - 如何根据用户输入动态计算和绘制画布边框
- amazon-web-services - S3 前缀事件触发器
- python - 根据字母数字日期对目录列表进行排序
- angular - Angular 使用身份服务器进行身份验证,然后发出 http 请求