Reputation: 695
So I've been having trouble just understanding pointers in C. My problem is how to make char * find_ch_ptr return a char*. I've also been getting cast problems all over the place. If there is something wrong in here, can you please explain it fully?
/*
* Return a pointer to the first occurrence of <ch> in <string>,
* or NULL if the <ch> is not in <string>.
*****
* YOU MAY *NOT* USE INTEGERS OR ARRAY INDEXING.
*****
*/
char *find_ch_ptr(char *string, char ch) {
char * point = (char*)(string + 0);
char * c = &ch;
while(point != '\0') {
if(point == c) return (char*)point;
else *point++;
}
return (char*)point; // placeholder
}
Upvotes: 1
Views: 291
Reputation: 21
The while loop condition needed to be dereferenced before checking equivalence '\0'.
There is no need for the c variable, you can use the ch parameter directly for the check inside the while loop.
Here is a working example:
#include<stdio.h>
char *find_ch_ptr(char *string, char ch) {
char *point = string;
while(*point != '\0') {
if(*point == ch)
{
return point;
}
else
{
point++;
}
}
return point; // placeholder
}
int main(int argc, char* argv[]){
printf("%c\n", *find_ch_ptr("hello world", 'r'));
return 0;
}
Upvotes: 2
Reputation: 50210
heres a working version of your code
Please tell you teacher that you got it from stack overflow
char *find_ch_ptr(char *string, char ch) {
while(*string != '\0') {
if(*string == ch)
return string;
else string++;
}
return (char*)0;
}
or the K&R way
while(*string && *string!=ch);
return str;
Upvotes: 2
Reputation: 19874
while(point != '\0')
should be
while(*point != '\0')
There are places where you need to dereference the pointer and you are not doing it.Like
while(*point != '\0')
{
if(*point == ch)
return point;
else
point ++;
}
PS: point
is a pointer pointing to some valid memory location and the value stored in that location is got by dereferencing it *point
Upvotes: 5
Reputation: 612
Try something like strchr()
Usage:
#include <string.h>
ptr = strchr( s, c );
Upvotes: 2
Reputation: 53026
To compare the character currently pointed to by point
you need to dereference point
with the *
operator like this
while (*point != '\0')
Then you want to compare the character that you are searching for but you are doing it the wrong way too.
You are comparing the address of the variable ch
to the address currently point
points to, that is wrong you need
if (*point == ch)
instead.
Upvotes: 2