just brushing up on some C for a class and I’ve run across a little something that makes me scratch me head. For this code:
char * findString(const char * s){
/* Allocate space */
char * ret = malloc(strlen(s) + 1);
/* Copy characters */
char * n;
n = ret;
for ( ;*s != 0; s++)
if (isLetter(*s))
*n++ = *s;
*n = 0;
/* return pointer to beginning of string */
return ret;
}
(We’re just assuming an isLetter that returns a 1/0).
The idea of the snippet is to take a string with a bunch of crap in it, and return a string that contains only the letters.
So, how does ‘ret’ work in this instance? I’m very confused by the returning of ‘ret’ when ‘n = ret’ is declared above the for loop and ‘ret’ never gets set to anything afterwards. Obviously I’m missing something here. Help!
-R. L.
both
retandnare pointers to the same block of memory. their ‘values’ are simply memory addresses — when you change*n, you change*ret, even thoughnandretretain their original values.note that the loop increments
n, and then after the loop sets the last character to 0 (to null terminate the string). Now,npoints to the end of the string — but sinceretwas never changed it still points to the beginning of the memory that youmalloced before the loop. When you return it, you’re returning a pointer to the new string which is the string you passed to the function, minus all non-letters.Note that after this function returns, it is the caller’s responsibility to
free()the memory allocated by the function, lest ye roam into memory leaks.