无法在 getline() while 循环之外打印 char**

Can't print char** outside of getline() while loop

尝试使用 getline() 从命令行参数读取文件并存储到 char** 中,但是当我尝试像使用 printf() 一样访问内部数据时,它什么也不打印。尽管 printf() 在每次 getline() 后的 while 循环中工作正常。

非常感谢任何帮助!

int main (int argc, char* argv[])
{
    //open file
    FILE *stream = NULL;
    char *line = NULL;
    size_t len = 0;
    ssize_t nread;
    if (argc != 2)
    {
        fprintf(stderr, "Usage: %s <file>\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    stream = fopen(argv[1], "r");
    if (stream == NULL)
    {
        perror("fopen");
        exit(EXIT_FAILURE);
    }

    //read file line by line
    char ** input = NULL;
    int i = 0;
    int j = 0;
    while ((nread = getline(&line, &len, stream)) != -1)
    {
        j++;
        input = (char **)realloc(input, sizeof(char*) * j);
        input[i] = (char *)malloc(sizeof(char) * strlen(line));
        input[i] = line;

        //print each line (PRINTS FINE)
        printf("%s",input[i]);
        i++;
    }

    //print each line outside of while loop (PRINTS NOTHING)
    for (int z = 0; z < j ; z++)
    {
        printf("%s",input[z]);
    }
}

欢迎尝试使用类似这样的任何 .txt 文件

./a.out input.txt

您的问题是无法打印。正在读取和存储中。

  1. sizeof(char) * strlen(line) 必须是 sizeof(char) * (strlen(line) + 1)(您没有为 NULL 终止符分配 space)。事实上,(strlen(line) + 1) 就足够了(请参阅@user3629249 的评论),甚至 (len + 1)(因为 len 保存读取字符串的长度)。

  2. input[i] = line; 不会创建字符串的副本。您必须使用 strcpy(input[i], line);.

  3. 最后一定要free(line)在最后。