strcmp的给分段错误 [英] strcmp giving segmentation fault
本文介绍了strcmp的给分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的code给分段错误
的#include<&stdio.h中GT;
#包括LT&;&signal.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&unistd.h中GT;
#包括LT&;&string.h中GT;诠释主要(无效){
字符*搞定;
scanf函数(%S,获得);
INT K = STRCMP(萨钦,获得);
的printf(%D,K);
}
感谢您的帮助;
解决方案
的char *搞定;
以上语句定义 GET
是一个指向一个字符。它可以存储类型字符
,而不是性格本身的一个对象的地址。现在的问题是既 scanf函数
和 STRCMP
电话。您需要定义一个字符数组来存储输入的字符串。
的#include<&stdio.h中GT;
#包括LT&;&string.h中GT;诠释主要(无效){
//假设最大字符串长度40
// +1由scanf函数添加终止空字节 焦炭得到[40 + 1]; //40年代%是指写最多40个字符
//入缓冲区得到,然后添加空字节
// 最后。这是为了防止由缓冲区溢出
// scanf函数的情况下,输入字符串是去专卖店偏大 scanf函数(%40多岁,获得);
INT K = STRCMP(萨钦,获得);
的printf(%D,K); 返回0;
}
this is my code giving segmentation fault
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(void) {
char *get;
scanf("%s", get);
int k = strcmp("sachin", get);
printf("%d", k);
}
thanks for any help;
解决方案
char *get;
The above statement defines get
to be a pointer to a character. It can store the address of an object of type char
, not a character itself. The problem is with both scanf
and strcmp
call. You need to define an array of characters to store the input string.
#include <stdio.h>
#include <string.h>
int main(void) {
// assuming max string length 40
// +1 for the terminating null byte added by scanf
char get[40+1];
// "%40s" means write at most 40 characters
// into the buffer get and then add the null byte
// at the end. This is to guard against buffer overrun by
// scanf in case the input string is too large for get to store
scanf("%40s", get);
int k = strcmp("sachin", get);
printf("%d", k);
return 0;
}
这篇关于strcmp的给分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文