c - Realloc:尝试存储字符串的下一个大小无效
问题描述
我只是在从文件中获取字符串时遇到问题。字符串每行列出一个,并受换行符的限制。我试图将它们存储在一个动态的字符串数组中,并收到一个无效的下一个大小错误,然后在第三个字符串之后中止。
我正在使用结构字典将大小存储在整数变量中,并将单词存储在字符串数组中。
代码是:
struct Dictionaries {
char** words;
int size;
};
typedef struct Dictionaries dictionary;
dictionary get_dict (FILE* fp) {
dictionary* dict = malloc(sizeof(dictionary));
dict->size = 0;
int strSize = 0;
dict->words = (char**) malloc(sizeof(char*));
dict->words[dict->size] = malloc(sizeof(char));
while(1) {
char c = fgetc(fp);
if (c == EOF ){
break;
}
if (c == '\n') {
dict->words[dict->size][strSize] = '\0';
strSize = 0;
dict->size++;
dict->words[dict->size] = malloc(sizeof(char));
dict->words = (char**) realloc(dict->words, (dict->size+1) * sizeof(char*));
} else {
strSize++;
//printf("%d\n", strSize);
//printf("%d\n", dict->size);
dict->words[dict->size] = (char*) realloc(dict->words[dict->size], (strSize+1) * sizeof(char));
dict->words[dict->size][strSize -1] = c;
}
}
return *dict;
}
PS抱歉格式不好,我第一次使用这个网站。
解决方案
推荐阅读
- java - 当我能够从 Kafka 恢复数据时,HBase ASYNC WAL
- google-chrome - 使 Chrome Devtools 设备大小与物理设备大小匹配
- javascript - 将字符串(日期)转换为格式 D, d MY
- neural-network - 对 NeRF 中的 get_rays 函数感到困惑
- node.js - 有没有办法解决这个错误
- node.js - 请求对象的未定义值
- capl - 如何将消息的值从十六进制转换为十进制?
- javascript - Karma Istanbul 仅生成一个文件夹的覆盖范围
- google-app-engine - 在 App Engine/meteor-files 上流星多个实例
- c# - 在 WPF Prism 应用程序中无法识别 onActivated 事件处理程序