gpt4 book ai didi

c - 运行时错误 : Segmentation fault (core dumped)

转载 作者:太空宇宙 更新时间:2023-11-04 02:02:16 25 4
gpt4 key购买 nike

我正在尝试编写一个程序,从输入行中删除尾随空格/制表符(来自 K&R 的练习 1-18)。

/* Write a program to remove trailing blanks and tabs from each
line of input, and to delete entirely blank lines. */

#include <stdio.h>
#define MAXLINE 1000

int gettline(char s[], int lim);

main()
{
int len, i;
char line[MAXLINE];
while ((len = gettline(line, MAXLINE)) > 0)
for(i=0; i<len-1; ++i){
if (line[i]!= ' ' && line[i]!='\t')
printf("%s", line[i]);
}
printf("\n");
return 0;
}

/* gettline: read a line into s, return length */
int gettline(char s[], int lim)
{
int c, i;
for (i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
s[i] = c;
if (c == '\n'){
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}

当我运行它时,出现错误 Segmentation fault (core dumped)。我查看了其他一些具有相同主题的 SO 问题(1234、..),但它们对于我的水平来说太复杂了。我只知道错误意味着我试图访问我不允许访问的部分内存。我不确定在我的案例中到底发生了什么

最佳答案

seg fault的原因应该是这样的:

    for(i=0; i<len-1; ++i){
if (line[i]!= ' ' && line[i]!='\t')
printf("%s", line[i]);
}

由于 %sprintf() 需要一个 char * 参数,但您传递了一个字符。将其更改为 printf( "%c", line[i] ); 它应该会运行。

但是它仍然不会按照您所说的那样执行(“删除尾随空格/制表符”),因为您不会打印任何空格或制表符,“Hello World ”将变为“HelloWorld”

关于c - 运行时错误 : Segmentation fault (core dumped),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25745948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com