【问题标题】:Using getline with a global variable将 getline 与全局变量一起使用
【发布时间】:2016-03-17 15:59:20
【问题描述】:

我将阅读几行文本,所以我想将它保存在一个全局变量中。我做了这样的事情:

#include <stdbool.h>
#include <stdio.h>
static char currentLine[MAX_LINE_LENGTH];

static bool readNextLine(void)
{
    return getline(&currentLine, NULL, stdin);
}

我得到的错误是

cc -Wno-unused-function -Wno-unused-variable -O2 -MD -MP -Wall -Werror -c src/parse.c -o build/parse.o
src/parse.c: In function ‘readNextLine’:
src/parse.c:14:20: error: passing argument 1 of ‘getline’ from incompatible pointer type [-Werror=incompatible-pointer-types]
     return getline(&currentLine, NULL, stdin);
                    ^
In file included from src/parse.c:2:0:
/usr/include/stdio.h:678:20: note: expected ‘char ** restrict’ but argument is of type ‘char (*)[100000]’
 extern _IO_ssize_t getline (char **__restrict __lineptr,

我做错了什么?

【问题讨论】:

  • man getline: If *lineptr is NULL, then getline() will allocate a buffer for storing the line, which should be freed by the user program. (In this case, the value in *n is ignored.) Alternatively, before calling getline(), *lineptr can contain a pointer to a malloc(3)-allocated buffer *n bytes in size. TL;DR: 你不能那样做。
  • 将错误的类型传递给getline,这就是您收到错误消息的原因。指向指针和指向数组的指针都是不同的。

标签: c getline


【解决方案1】:

getline(&amp;currentLine, NULL, stdin); 期望操纵两件事:char * 分配的内存和size_t 类型的大小。所以这两个项目的地址都需要传递。以下代码失败,因为getline() 无法更改currentLine[] 的地址,也没有分配。

char currentLine[MAX_LINE_LENGTH];
getline(&currentLine, NULL, stdin); // fails

相反

#include <stdbool.h>
#include <stdio.h>

static char *currentLine = NULL;
static size_t currentLineSize = 0;

// true when a line is read
static bool readNextLine(void) {
    return getline(&currentLine, &currentLineSize, stdin) >= 0;
}

注意:健壮的代码将在最终使用缓冲区后执行最终的free()

static void readNextLine_CleanUp(void) {
    free(currentLine);
    currentLine = NULL;
    currentLineSize = 0;
}

Ref

【讨论】:

    【解决方案2】:

    为变量使用正确的类型并正确使用getline()

    • 第一个参数必须是指向char的指针。
    • 第二个参数不能是NULL
    • 正确使用返回值判断调用是否成功。

    修改后的代码:

    #define _GNU_SOURCE
    #include <stdbool.h>
    #include <stdio.h>
    #include <stdlib.h>
    static char *currentLine = NULL;
    
    static bool readNextLine(void)
    {
        size_t dummy = 0;
        free(currentLine);
        currentLine = NULL;
        return getline(&currentLine, &dummy, stdin) >= 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-09
      相关资源
      最近更新 更多