当我运行此代码时,出现错误 segmentation fault (core dumped)
。我看到错误在于“printf("%c",first(s));”,似乎这不是将 char/string 传递给函数的正确方法?如果不是那么我的代码有什么问题?
#include <stdio.h>
char first(char *str);
char first(char *str){
int L=0;
int a[127]={0};
for (int i=0; i<127; i++){
a[i]=i+1;
}
while (str != '\0'){
for(int d=1; d<127; d++){
if(str[L]==(char)d){
if (a[L]>0){
a[L]=0;
L++;
break;
}
else if(a[L]==0){
a[L]=-1;
L++;
break;
}
else{
L++;
break;
}
}
}
}
for(int i=0; i>127; i++){
if(a[i]==0)
return (char)(i+1);
}
return '\0';
}
int main()
{
char s="blazqnqbla";
printf("%c", first(s));
return 0;
}
最佳答案
不确定您想在这里做什么,因此无法帮助解决算法。
要解决核心转储问题,您需要做两件事。
定义字符指针为
char *s="blazqnqbla"; // you had defined it as char s="..."
将 while 循环条件从
while (str!= '\0')
更改为while (str[L]!= '\0')
通过这些更改,程序可以正常退出。函数first
仍然存在一些算法问题。它没有给出任何有意义的输出。
关于c - 程序运行时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52941552/