【发布时间】:2020-03-22 06:17:01
【问题描述】:
我有一个动态数组,其中包含一个包含“\n”字符的字符串,因此该字符串由多行组成。我正在尝试提取线条并将它们全部放入 2D char 数组中,但出现分段错误。
这是我的代码:
char *input_lines = malloc(MAX_LINE_LEN*sizeof(char));
input_lines = extractInput(MAX_LINE_LEN, input_file);
char inputLines_counted[lineCount_input][MAX_LINE_LEN];
char *t = strtok(input_lines, "\n");
for(i = 0; i < lineCount_input; i++) {
strcpy(inputLines_counted[i], t);
// printf("%s\n", inputLines_counted[i]);
t = strtok(NULL, "\n");
}
创建动态数组后,我使用extractInput(MAX_LINE_LEN, input_file) 函数用包含多行的字符串填充input_lines 数组。
这里是提取函数:
char *extractInput(int len, FILE *file) {
char tmp[len];
char *pos;
char *input_lines = malloc(len*sizeof(char));
char *lines;
while(fgets(tmp, len, file)) {
// if((pos = strchr(tmp, '\n')) != NULL) {
// *pos = ' ';
// }
input_lines = realloc(input_lines, (strlen(input_lines) + len)*sizeof(char));
strcat(input_lines, tmp);
}
return input_lines;
}
为什么会出现段错误?
【问题讨论】:
-
计算 \n 之间的字符数,以确保 MAX_LINE_LEN 足够大并记住结尾 \0 需要空间
-
@AndersK 我的作业,最大行长是一个给定的值,我已经在代码中声明了它。
-
是的,但 was 是您在 input_lines 中的实际长度
-
@AndersK 好吧,每行都会有所不同
-
但我猜你检查了你没有显示的代码(extractInput)
标签: c arrays tokenize dynamic-arrays strtok