简体   繁体   English

搜索字符串中的公共字符并返回指向公共字符的指针(不使用strpbrk)

[英]Search common characters in strings and return pointer to the common character (without using strpbrk)

Following code finds the common character in two strings and returns a pointer to the common string if any. 以下代码在两个字符串中查找公共字符,并返回指向公共字符串(如果有)的指针。 I'm trying to emulate the function strpbrk without using any builtin functions or subscripts. 我试图在不使用任何内置函数或下标的情况下模拟strpbrk函数。

#include <stdio.h>
#include <stdlib.h>



char *find_char( char const *source, char const *chars ){

    char* str1;
    char* str2;

    if (source == NULL || chars == NULL)
        return NULL;

     else {

        for( *str1=&source != '\0'; ++str1;){
            for( *str2=&chars != '\0'; ++str2;){

                if (*str1 == *str2)

                    return str1;

                else return NULL;}

    }

}
}

char* main(){  
    char const *source = "ab";
    char const *chars = "bc";
    find_char(source, chars);
}

But I'm getting the following error 但我收到以下错误

Running "/home/ubuntu/workspace/hello-c-world.c" 运行“ /home/ubuntu/workspace/hello-c-world.c”
bash: line 12: 29755 Segmentation fault "$file.o" $args bash:第12行:29755分段错误“ $ file.o” $ args
Process exited with code: 139 进程退出,代码为:139

I am a beginner at C and learning how to manipulate pointers, please let me know what am I doing wrong and how I can strengthen my C programming skills, right now I'm mostly using Kenneth Reek's book "Pointers on C" 我是C的初学者,正在学习如何操作指针,请让我知道我在做错什么以及如何增强C编程技能,现在我主要使用Kenneth Reek的书“ C上的指针”

Thanks 谢谢

Various ìf logic and runaway pointer problems. 各种ìf逻辑和失控指针的问题。 Fixed code below: 固定代码如下:

char *find_char( char const *source, char const *chars ){

    char* str1;
    char* str2;

    if (source != NULL && chars != NULL) {
       for( str1=source; *str1; str1++){
           for( str2=chars; *str2; str2++){
               if (*str1 == *str2) return str1;
           }
       }
    }
    return NULL;
}

char* main(){  
    char const *source = "ab";
    char const *chars = "bc";
    char *x;
    x = find_char(source, chars);
    if (x != NULL) printf("%c", *x);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM