我对 C 很陌生,所以如果这是一个愚蠢的问题,我深表歉意。我遇到了段错误,当我运行 gdb 时,我没有像通常那样获得行号来演示导致错误的原因。相反,我得到了一些类似的东西:
0x00000000004012ff in find_any_ptr ()
我正在编写一个方法,返回一个指针,该指针指向给定字符串
中stop
中第一次出现的任何字符,如果是,则返回NULL
string
不包含任何字符。
char *find_any_ptr(char *string, char* stop){
char* ch1 = string;
char* ch2 = stop;
int retComp = strlen(string);
char* retChar;
while(*ch2 != '\0'){
int temp = 0;
while(*ch1 != '\0'){
if(*ch2 == *ch1){
if(temp < retComp){
*retChar = ch1;
retComp = temp;
}
}
temp++;
ch1++;
}
ch2++;
}
if(retComp == strlen(string)){
return NULL; //NULL has been defined elsewhere
}else{
return retChar;
}
}
如果有人发现根本问题出在哪里,我将非常感谢您的帮助。 :)谢谢!
最佳答案
将 *retChar = ch1;
更改为 retChar = ch1;
即。当 retChar
指针未初始化为某些内容时,您将取消引用它,并且您可能只是希望它分配 ch1
指针的值(地址而不是它的字符)指着)。
关于c - 我的段错误发生在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42797936/