Zefyre,
Your code has several problems. One of which is that it does not
actually do what strchr() does. We'll get to that in a moment.
First, the reason for your crash:
You declare a char pointer called return_value. A pointer has to point
at something. You don't initialize it, and you don't point it at
anything valid. Therefore, it is very likely to crash if you try to
use it. Note that you crash when your code succeeds in matching
needle. This condition allows your code to run the part where you try
to set return_value[count_b]. Since this location is a pointer off
into la-la land, you crash. To use a char pointer this way, you need
to allocate some memory for it to point at. For example, malloc().
However, all of this is actually irrelevant. You don't need any of
this to duplicate strchr. To work like strchr, your code needs to
return a pointer into haystack. The way your code is currently
written, even if you fix the crash, you will simply return the
character you were originally looking for. The point of strchr is to
return a pointer that show where in the original string the character
appears.
MSDN Library Reference for strchr
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_strchr.2c_.wcschr.2c_._mbschr.asp
Here is a commented implementation of strchr:
char *my_strchr(char needle, char *haystack)
{
// Declare some char pointers
char *return_value;
char *cp;
// Initialize return value
return_value = NULL;
// Make sure haystack is valid
if(haystack != NULL)
{
// Set pointer to beginning of haystack
cp = haystack;
// Run until we either find a match or
// get to the end of haystack.
while((*cp != '\0') && (return_value == NULL))
{
// If we found a match, set return value
// and exit the loop
if(*cp == needle) return_value = cp;
// Advance cp
cp++;
}
}
// If we didn't find a match, return_value is
// still NULL. Otherwise, it is pointing at the
// first matching character in haystack.
return(return_value);
}
In your example above, return_value would be " EbertSoft-UICI".
I hope this clarifies things for you. Please let me know if you need
any of the techniques in the example explained.
Search strategy: None. I've just done this before!
- Hammer |
Clarification of Answer by
hammer-ga
on
04 Feb 2004 12:32 PST
You're used to working in a higher level language, like VB, aren't you? *wink*
You are not dealing with String objects here. You are dealing with
pointers into memory. A pointer is a number that represents a memory
address, not a string value. cp = haystack sets cp to point at the
same address as haystack. That address represents the beginning of a
chunk of memory which contains your string value. When cp = haystack,
cp points at the first letter in haystack. When cp = haystack + 1, cp
points at the second letter in haystack, and so on. You have to be
careful with this in C. You can keep doing cp++ and run cp out past
the end of haystack and off into wherever. C won't stop you!
- Hammer
|