以下代码查找两个字符串中的公共(public)字符,并返回指向公共(public)字符串的指针(如果有)。我试图在不使用任何内置函数或下标的情况下模拟函数 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);
}
但是我收到以下错误
Running "/home/ubuntu/workspace/hello-c-world.c"
bash: line 12: 29755 Segmentation fault "$file.o" $args
Process exited with code: 139
我是 C 初学者,正在学习如何操作指针,请让我知道我做错了什么以及如何增强我的 C 编程技能,现在我主要使用 Kenneth Reek 的书“Pointers on C”
谢谢
最佳答案
各种ì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);
}
关于c - 搜索字符串中的公共(public)字符并返回指向公共(public)字符的指针(不使用strpbrk),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36518505/