【发布时间】:2014-04-10 05:52:52
【问题描述】:
嘿,我想知道是否有人知道如何解决这个问题。我想获取用户输入并从中执行一些操作。现在我在 scanf 线上遇到了段错误,无法弄清楚原因。之后,我尝试将两个数组连接在一起,并提供帮助。
char command[1000];
char firstName[1000];
char lastName[1000];
char month[1000];
char day[1000];
while( strcmp("quit", &command[0]) != 0 ){
fflush(stdin);
printf("Please enter next command: ");
scanf("%s", command); // <--- This is tested and working
if(strcmp(&command[0], "quit") == 0){
break;
}
else if(strcmp(&command[0], "empty") == 0){
empty();
}
else if(strcmp(&command[0], "append") == 0){
printf("--------->1");
scanf("%s %s %s %s", firstName, lastName, month, day); //<--- This line :(
printf("--------->2"); // <---- This never prints
char fullName[2001];
char birthday[2001];
malloc(strlen(firstName) + 1);
strcpy(firstName, fullName);
malloc(strlen(lastName) + 1);
strcpy(lastName, fullName);
printf("%s", fullName);
从终端:
gregs-mbp:desktop GregR$ ./blist
Please enter next command: append greg r jan 02
Segmentation fault: 11
gregs-mbp:desktop GregR$ ./blist
Please enter next command: append
--------->1greg r jan 02
Segmentation fault: 11
gregs-mbp:desktop GregR$
gregs-mbp:desktop GregR$ ./bList
Please enter next command: quit
All done
【问题讨论】:
-
您的代码没有给出分段错误。你能给出你得到输出分段错误的输入吗?
-
您的代码中有其他错误和对
malloc的异常调用,但scanf行没有任何问题。 -
@R Sahu - 就像
gets没有任何问题一样。我总是想知道为什么人们跳上gets,却对scanf("%s"一言不发 -
他应该在 ---> 箭头打印中添加换行符,以阐明段错误实际发生的位置。
-
strcmp 将因“append Greg r Jan 02”和“append”而失败。那么它就会将条件传递给我们看不到的东西。这就是第一种情况下的段错误。
标签: c segmentation-fault malloc scanf