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.
#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"
bash: line 12: 29755 Segmentation fault "$file.o" $args
Process exited with code: 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"
Thanks
Various ìf
logic and runaway pointer problems. 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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.