我正在尝试K&R C编程语言书第一章的练习24,但我遇到了某个错误。练习是采用C程序来查找基本错误,例如大括号或引号不匹配,因此我所做的工作是使用计数器在输入中看到某个字符时增加和减少,然后在最后打印这些字符。不过,我正在发生的事情是,这些计数器中的两个计数器提供了可笑的大值(大于输入文件本身中的字符数),并且每次在同一编译器上执行代码时都会更改它们。这是我的代码,执行此操作的变量是singleQuote
和escSequence
:
#include <stdio.h>
#define maxLine 1000
#define True 1
#define False 0
int main() {
int c, i, braces, comments, escSequence, singleQuote, doubleQuote = 0;
char input[maxLine];
int insingleQuote, indoubleQuote = False;
for (i=0; i<maxLine-1 && (c=getchar()) != EOF; ++i) {
input[i] = c;
}
input[i] = '\0';
for (i=0; input[i] != '\0'; ++i) {
if (input[i] == '{') {
++braces;
}
if (input[i] == '}') {
--braces;
}
if (input[i] == '\'' && insingleQuote == True) {
insingleQuote = False;
--singleQuote;
}
else if (input[i] == '\'') {
insingleQuote = True;
++singleQuote;
}
if (input[i] == '\\' && insingleQuote == True && ((input[i+1] != 'n') || (input[i+1] != '\\') || (input[i+1] != '\'') || (input[i+1] != '\"') || (input[i+1] != 't') || (input[i+1] != 'b'))) {
++escSequence;
}
if (input[i] == '\"' && indoubleQuote == True) {
indoubleQuote = False;
--doubleQuote;
}
else if (input[i] == '\"') {
indoubleQuote = True;
++doubleQuote;
}
}
printf("%s\n", input);
printf("Number of unmatched braces: %d\n", braces);
printf("Number of unmatched single quotes: %d\n", singleQuote);
printf("Number of unmatched double quotes %d\n", doubleQuote);
printf("Number of incorrect escape sequnces %d\n", escSequence);
return 0;
}
答案 0 :(得分:3)
int c, i, braces, comments, escSequence, singleQuote, doubleQuote = 0;
只有doubleQuote初始化为0。其余的则保留一个随机值,具体取决于它们在内存中的位置以及之前的状态。
->不确定的行为。在使用它们之前先初始化所有值,然后问题就会消失。