【发布时间】:2021-12-27 16:23:51
【问题描述】:
我正在尝试学习 C 指针传递。所以请原谅我的无知。
我想在函数中分配一个二维动态分配的字符串数组。 函数签名是无效的,所以参数是引用的。
测试文件包含这两行。
I am testing.
This is not an empty file.
这是我到目前为止所做的。
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void read_lines(FILE *fp, char** lines, int *num_lines) {
ssize_t read;
char * line = NULL;
size_t len = 0;
*num_lines = 0;
while ((read = getline(&line, &len, fp)) != -1) {
if (*num_lines == 0) {
// For the first time it holds only one char pointer
*lines = malloc(sizeof(char *));
} else {
// Every time a line is read, space for next pointer is allocated
*lines = realloc(*lines, (*num_lines) * sizeof(char *));
}
// allocate space where the current line can be stored
*(lines + (*num_lines)) = malloc(len * sizeof(char));
// Copy data
strcpy(*(lines + (*num_lines)), line);
printf("Retrieved line of length %zu:\n", read);
printf("%s\n", line);
(*num_lines)++;
// After first line subsequent lines get truncated if I free
// the storage here, then subsequent lines are not read completely
//if (line) {
// free(line);
//}
}
if (line) {
free(line);
}
}
int main(void)
{
FILE * fp;
char *array;
int num_lines;
fp = fopen("file.txt", "r");
if (fp == NULL)
exit(EXIT_FAILURE);
read_lines(fp, &array, &num_lines);
printf("After returning\n");
// Intend to access as array[0], array[1] etc
// That's not working
// If I access this way then I get seg violation after first line
printf("%s\n", &array[0]);
fclose(fp);
}
我的问题与代码一致:
- 为什么我不能在 while 循环中为
line释放存储空间? - 如何访问
main中返回的二维数组?array[0]array[1]似乎不起作用?我想做类似的事情。 - 为什么我现在这样做会产生段错误?
更正的代码将帮助我理解。此外,任何人都可以提供任何好的参考来澄清 C 的这些概念,我们将不胜感激。
【问题讨论】:
-
line在第一个*line = ...上为 NULL。期待问题!