【问题标题】:Search common characters in strings and return pointer to the common character (without using strpbrk)搜索字符串中的常用字符并返回指向常用字符的指针(不使用 strpbrk)
【发布时间】:2016-04-09 14:59:48
【问题描述】:

以下代码在两个字符串中查找公共字符,并返回一个指向公共字符串的指针(如果有)。我正在尝试在不使用任何内置函数或下标的情况下模拟函数 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);
}

但我收到以下错误

运行“/home/ubuntu/workspace/hello-c-world.c”
bash:第 12 行:29755 分段错误“$file.o”$args
进程退出,代码:139

我是 C 的初学者,正在学习如何操作指针,请告诉我我做错了什么以及如何加强我的 C 编程技能,现在我主要使用 Kenneth Reek 的书“C 上的指针”

谢谢

【问题讨论】:

  • 我无法将 const char* 分配给 char *

标签: c string bash pointers


【解决方案1】:

各种ìf 逻辑和失控指针问题。修复代码如下:

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);
}

【讨论】:

  • 你能解释一下失控的指针问题吗?或建议我可以在哪里获得正确的指针方向。谢谢
  • @SundasWaheed 主要问题出在for 语句中。循环不会按预期终止,因为*str2=&amp;chars != '\0'; 不仅用&amp;chars(=chars 的地址)覆盖了*str2(=“地址str2 处的内存位置”),而且此外,此分配将从不返回 0(因为&amp;chars 是一个非零地址),因此循环将永远继续(导致分段错误)。您实际需要做的是用chars 的地址初始化指针str2,就像我在答案中的代码中所做的那样。同样适用于带有str1 的另一个for 循环。
  • @SundasWaheed 这完全是关于str2*str2chars&amp;chars 之间的区别,以及代码所指的内容。地址,或该地址指向的内存内容。
猜你喜欢
  • 2011-06-17
  • 2020-03-25
  • 1970-01-01
  • 2013-08-02
  • 2015-10-10
  • 2015-06-22
  • 1970-01-01
  • 2021-08-03
  • 2016-12-30
相关资源
最近更新 更多