Reputation: 3652
I am trying to implement a function, that searches for the first occurrence of a passed string in a global variable. When found, I want it to return the matching char as a pointer.
This however, doesn't work:
warning: return makes pointer from integer without a cast [enabled by default]
char *find(const char *s)
{
int i = 0;
const char *ptr = s;
while(ptr[i])
{
//wordList is a global struct with a string
if(ptr[i] == wordList->search[0])
{
return ptr[i];
}
else i+=1;
}
return NULL;
}
Upvotes: 1
Views: 135
Reputation: 7833
You want to return &ptr[i]
- your code is returning the value of the character found cast to a pointer.
Also, you are taking in a const char*
and returning a char *
- you should probably fix that - either change the return type or s
and ptr
. Also, you don't need ptr
- you can do the whole thing dereferencing s
directly.
oh, and if you stick with the consts and we are being picky, then it should probably be const char* const s
Upvotes: 3
Reputation: 106032
ptr[i]
is of type char
. You need to return a char
pointer from your function as its return type is char *
. Use
return &ptr[i];
As Bit Fiddling Code Monkey pointed in his comment, better to change the return type of your function
const char *find(const char *s) { ... }
Upvotes: 1