Drunk Coding

Dec 17, 2008 21:06


I have a margarita in me, and I'm starting on a bottle of wine, so I'm clearly not in the right frame for this. However, I'm trying to code up some string functions and I'm a little confused about const char *.

First, let's say I have a function:

const char *GetFirstSubstring(char *instring);

The idea here is to pass in a valid null terminated string, and then do the search for whatever substring I'm looking for (let's say the first n characters up to a space, tab, or terminating null), and return that. My naive implementation would be:

const char *GetFirstSubstring(char *instring)
{
static returnString[MAX_LENGTH];

if((!instring)||(strlen(instring) >= MAX_LENGTH))
return NULL;

int i=0;
while((instring[i] != '\0')&&(instring[i] != ' ')&&(instring[i] != '\t')
{
returnString[i]=instring[i];
i++;
}
returnString[i] = '\0';

return (const char *)returnString;
}

Which seems fine, because the memory is owned locally and totally managed by the function.

However, say I want to write another function:

bool CaselessCompare(const char * s1, const char * s2);

This function takes two strings, does a tolower on all characters in them, and then tests for equality. That seems straightforward, but what if I call it with two internal calls to GetFirstSubstring?

result = CaselessCompare(GetFirstSubstring(string1),GetFirstSubstring(string2));

Since the strings are internal to GetFirstSubstring, won't the second call overwrite the results of the first and make CaselessCompare always return true?

How do I get around this?
Previous post Next post
Up