为什么我的代码会导致分段错误?
Why my code is causing the segmentation fault?
我尝试在 Visual stdio 中 运行 这个程序并使用 WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB
作为输入。在 运行 之后,它显示 Segmentation fault (core dumped).
如何解决?
#include <stdio.h>
#include <string.h>
int main()
{
char string[201];
int i, j;
scanf("%s",string);
for(i=0;i<strlen(string); i++){
if(string[i]=='W' && string[i+1]=='U' && string[i+2]=='B'){
for(int k=i; k<i+3; k++){
string[k]='o';
i=i+2;
}
}
}
puts (string);
}
我想知道我的程序哪里出了问题
当 I 等于 strlen(string) - 1
时,您无法访问 string[i+2]
。您可以访问 string[i+1] ,这将是终止的 nul 字符。
改变你for循环的上限
我尝试在 Visual stdio 中 运行 这个程序并使用 WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB
作为输入。在 运行 之后,它显示 Segmentation fault (core dumped).
如何解决?
#include <stdio.h>
#include <string.h>
int main()
{
char string[201];
int i, j;
scanf("%s",string);
for(i=0;i<strlen(string); i++){
if(string[i]=='W' && string[i+1]=='U' && string[i+2]=='B'){
for(int k=i; k<i+3; k++){
string[k]='o';
i=i+2;
}
}
}
puts (string);
}
我想知道我的程序哪里出了问题
当 I 等于 strlen(string) - 1
时,您无法访问 string[i+2]
。您可以访问 string[i+1] ,这将是终止的 nul 字符。
改变你for循环的上限