
another newbie question: strncpy function
Quote:
>>char *strncpy(char *s1, const char *s2, int n) { int x; for(x=0; x<n;
>>x++) { if(*ptr2) s1[x]=*s2++; else s1[x]='\0'; } return s1; }
>>it seems to work, but it seems like it could be better...
As Robert mentioned, if(*ptr2) looks fishy. How did this function manage to
work? You probably meant if(*s2) instead.
Quote:
>char *strncpy( char *s1, const char *s2, int n)
>{
> int x;
> for ( x = 0; ( x < n) && *s2;)
> *s1++ = *s2++;
> if ( x < n)
> *s1 = 0;
> return s1;
>}
>(And, yes, it's possible to fold my 'if' statement into the loop, but I
>don't feel it would look very good, nor would it gain you much).
Except that, now, it's not a valid implementation of strncpy().
#include <stddef.h>
char * my_strncpy(char *s1, const char *s2, size_t n)
{
while (n--) *s1++ = (*s2) ? (*s2++) : (*s2);
return s1;
Quote:
}
would be the implementation of my choice, but it shouldn't be
significantly faster (or slower) than the (corrected) version of the
function from the original post. Any attempt to do loop unrolling,
etc., would be classified as micro-optimization, which probably wouldn't
help, and if it did, the optimization wouldn't be portable to all
platforms anyway.
So, my advice is, if the version you have works correctly, stick with it.
--
http://www.cs.wustl.edu/~jxh/ Washington University in Saint Louis
Quote:
>>>>>>>>>>>>> I use *SpamBeGone* <URL:http://www.internz.com/SpamBeGone/>