Ok, so I have an assignment here from my professor. Here it is:
Write a function called strchr406. It is passed 2 parameters: a string and a char Here is the prototype for the function: char *strchr406(char str[], char ch); The function should return a pointer to the first instance of ch in str. For example:
char s[ ] = "abcbc";
strchr406(s, 'b'); // returns s + 1 (i.e., a pointer to the first 'b' in s)
strchr406(s, 'c'); // returns s + 2
strchr406(s, 'd'); // returns 0
He is asking us to write our own version of strchr using pointers. I looked up online for resources but none of it matches what he is asking us to do. I'm working with a group of other students, and none of us could figure this out.
How do we RETURN "s + 1"?
So far, I have this: (I also put it online if that's easier: https://repl.it/FVK8)
#include <stdio.h>
#include "string_problems.h"
int main() {
char s[ ] = "abcbc";
strchr406(s, 'b'); // returns s + 1 (i.e., a pointer to the first 'b' in s)
strchr406(s, 'c'); // returns s + 2
strchr406(s, 'd'); // returns 0
printf("this should return %s\n", strchr406(s, 'c'));
return 0;
}
char *strchr406(char str[], char ch) {
char *p = str;
int index = 0;
while (*str != ch) {
++str;
++index;
}
if (*str == ch) {
return p + index;
} else {
return 0;
}
}
I'm getting weird outputs. Any help is appreciated.