【问题标题】:Cannot read individual characters after running getline运行 getline 后无法读取单个字符
【发布时间】:2017-05-21 00:42:18
【问题描述】:

这是 getline 手册页中的代码 sn-p ,它工作得很好。

FILE* fp;
size_t len = 0;
char* line = NULL;
ssize_t read;
fp = fopen("test.txt", "r");
while ((read = getline(&line, &len, fp)) != -1) {
    printf("Retrieved line of length %zu :\n", read);
    printf("%s", line);
}

但是,当我尝试从行变量中访问单个字符时,例如:

while ((read = getline(&line, &len, fp)) != -1) {
    printf("Retrieved line of length %zu :\n", read);
    printf("%s", line);
    printf("%s", line[0]);
}

我遇到了分段错误(核心转储)错误。

【问题讨论】:

  • 我遇到了分段错误(核心转储)错误。在哪一行?您是否尝试在调试器中运行?提示:检查每个函数调用的返回值...
  • printf("%s", line[0]); 这一行,删除它会使程序再次运行
  • 我不确定getline 是否在末尾添加了正确的空终止符。如果 line 不是以 null 结尾的,printf("%s",line) 将读取到 line 数组的末尾,到达无效内存并导致访问冲突。
  • printf("%s", line[0]);这条线,删除它使程序再次工作 现在有一个线索。 line[0] 到底是什么?
  • @AndrewHenle 好吧,他已经说过了:)

标签: c getline


【解决方案1】:

这个:

printf("%s", line[0]);

不是如何打印一个字符。 %s 告诉 printf() 期待一个字符串,它在 C 中是 char 数组(相当于指向 char 的指针)。因此 char 被视为导致分段错误的字符串的地址。

这就是你想做的:

printf("%c", line[0]);

【讨论】:

  • 谢谢,它奏效了,我想主要使用字符只是 len 1 字符串的语言使我的想法变得愚蠢。错误消息在 C 中也很神秘。
猜你喜欢
  • 2019-10-15
  • 1970-01-01
  • 1970-01-01
  • 2017-12-28
  • 2020-02-27
  • 2013-08-23
  • 1970-01-01
  • 2021-12-05
相关资源
最近更新 更多