【发布时间】:2015-08-26 07:45:52
【问题描述】:
我下面用 C 编写的程序正在运行到某个点。但是,它停在我认为的无错误代码的中间。来自 Java,我是 C 的新手,所以任何帮助都将不胜感激。
#include <stdio.h>
#include <stdlib.h>
void getInput(char *input, const char *rs[]){// Args are the user input and our reserved words array.
printf(">>"); fgets(input, 1000, stdin);// Getting our normal command
int i;
for(i = 0; i < (int)sizeof(rs); i++){
if(strcmp(input, rs[i]) != 0){
printf("You said: %s", input); //PROGRAM BREAKS AFTER THIS LINE
}
}
printf("Size of \"input\" is: %d\n", sizeof(input));// Just checking the size of input
free(input);// Deallocating input since we won't need it anymore.
}
int main(){
char *input = malloc(500 * sizeof(char));// Command line input
const char *rs[1];// Reserved words array.
rs[0] = "print";
getInput(input, rs);
getch();
}
【问题讨论】:
-
我很抱歉代码格式不正确。我只是简单地复制和粘贴,结果就是这样。
-
0)
5001000大小不匹配。 1)sizeof(rs)和sizeof(input):它们是指针的大小。 -
i < (int)sizeof(rs);在 C 语言中,您无法仅通过指针知道数组中元素的数量。请注意,main()也接受argc参数以及*argv[]。 -
循环尝试多次执行,因为 a) 大小错误(如@BLUEPIXY 所说),b) 输入字符串与“print”不匹配,因为
fgets()将追加newline到输入字符串。 -
发布的代码编译不干净。编译时始终启用所有编译器警告。然后解决这些问题(不要隐藏它们)。除其他外,代码缺少#include
头文件。当参数是“long unsigned int”时,第 17 行的格式说明符为“%d”。我不知道你在哪里找到 'getch()' 但更好的调用是:'getchar()'