[英]Why do I get segmentation fault in my code?
I keep getting segmentation fault, how can I fix that. 我不断遇到细分错误,该如何解决。 I tryed more variants but I get segmentation fault everytime when I am using if statements.
我尝试了更多的变体,但是每次使用if语句时都会遇到分段错误。 My code is something similar with this:
我的代码与此类似:
#include <stdio.h>
#include <string.h>
int main()
{
int i;
char *sentence[300];
fgets(*sentence,300,stdin);
int length=strlen(*sentence);
for(i=0;i<length;i++){
if(sentence[i]=="a")
printf("qwer");
else if(sentence[i]=="b")
printf("asdf");
else if(sentence[i]=="c")
printf("zxcv");
// ...
}
return 0;
}
The first thing you're doing wrong is this: 您做错的第一件事是:
char *sentence[300];
It looks like you're trying to create a buffer of 300 characters, but what you're really doing is creating an array of 300 character pointers. 看起来您正在尝试创建300个字符的缓冲区,但实际上是在创建300个字符的指针数组。 Change that to:
更改为:
char sentence[300];
Then you want to change this: 然后您要更改此设置:
fgets(*sentence,300,stdin);
to 至
fgets(sentence,sizeof(sentence),stdin);
Then you want to change 那你想改变
int length=strlen(*sentence);
to 至
int length=strlen(sentence);
You need to have a good understanding of how strings work in C. If you haven't read a good introductory book for C, start there. 您需要对字符串在C中的工作方式有充分的了解。如果您还没有阅读关于C的入门书籍,请从那里开始。 C is not something you're going to pick up by just reading random pages on the web and StackOverflow.
仅通过阅读Web和StackOverflow上的随机页面就不会使用C。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.