在 C 语言中比较由 fgets() 变红的字符串的 \n 时出现分段错误
Getting segmentation fault while comparing the \n of a string that red by fgets() in C language
我正在编写一个程序来反转字符串中的单词,即 "abc def"
到 "def abc"
。
我使用 fgets()
读取输入。我正在使用:
for(j = i;((buff[i] != ' ') || (buff[i] != '\n'));i++ );
识别 space 或行尾。
但我遇到了分段错误。
单独检查 space,一切正常。
请帮我解决这个问题。
((buff[i] != ' ') || (buff[i] != '\n'))
这意味着 "keep going while the character is not a space or is not a newline"。
由于一个字符永远不可能同时是 space 和换行符,至少 一个 这些子条件将始终为真。让我们举几个例子:
value (value != ' ') (value != '\n') or'ed result
------- -------------- --------------- ------------
space false true true
newline true false true
'A' true true true
因此你有一个无限循环,这几乎可以肯定是导致你的问题的原因。
我建议您将 ||
替换为更正确的 &&
,如 "keep going while the character is both not a space and not a newline":
value (value != ' ') (value != '\n') and'ed result
------- -------------- --------------- -------------
space false true false
newline true false false
'A' true true true
我正在编写一个程序来反转字符串中的单词,即 "abc def"
到 "def abc"
。
我使用 fgets()
读取输入。我正在使用:
for(j = i;((buff[i] != ' ') || (buff[i] != '\n'));i++ );
识别 space 或行尾。
但我遇到了分段错误。
单独检查 space,一切正常。
请帮我解决这个问题。
((buff[i] != ' ') || (buff[i] != '\n'))
这意味着 "keep going while the character is not a space or is not a newline"。
由于一个字符永远不可能同时是 space 和换行符,至少 一个 这些子条件将始终为真。让我们举几个例子:
value (value != ' ') (value != '\n') or'ed result
------- -------------- --------------- ------------
space false true true
newline true false true
'A' true true true
因此你有一个无限循环,这几乎可以肯定是导致你的问题的原因。
我建议您将 ||
替换为更正确的 &&
,如 "keep going while the character is both not a space and not a newline":
value (value != ' ') (value != '\n') and'ed result
------- -------------- --------------- -------------
space false true false
newline true false false
'A' true true true