Comment on Ask HN: Favorite pointer tricks in C?Comments−Locke168915yInstead of using a while loop to iterate through a linked list, consider using a for loop. Node * iter; for (iter=root; iter != NULL; iter=iter->next) { /* iter->object; */ } A concise implementation of strlen size_t strlen(char * str) { char * cur; for(cur=str; *cur; ++cur); return (cur-str); } Reverse a string in-place. void reverse(char * str) { char *i,*j, tmp; for (i=str, j=(str+strlen(str)-1); i < j; ++i,++j) { tmp = *i; *i = *j; *j = tmp; }−visualphoenix15yShouldn't that be --j in your reverse function?Anyhow, when asked to write those on a blackboard, I typically do this: size_t strlen(char* start) { char* end=start; while(*end) ++end; return (end-start); } and void reverse(char* i) { char* j=(i+strlen(i)-1); for (; i < j; ++i,--j) { *i ^= *j; *j ^= *i; *i ^= *j; }−Locke168915yYup, --j.Also, the XOR version probably isn't worth the complexity.−visualphoenix15yTrue in practice, but on a blackboard during an interview, it obviates the need to recode for the follow-up "now reverse the string in place" request.−mrb15yYou have a bug in strlen: for(cur=str; cur; ++cur); should be: for(cur=str; *cur; ++cur);−Locke168915yRight you are. Wrote all those in the comment block. Fixed in an edit.−phsoftnet15y size_t strlen(char *s) { size_t i = 0; while(*s++) i++; return i; }−sfgfdhgfdshdhhd15yvoid strcpy(char s1, char s2) { while((s1++) = (s2++)); }
Comments
Instead of using a while loop to iterate through a linked list, consider using a for loop.
A concise implementation of strlen Reverse a string in-place.Shouldn't that be --j in your reverse function?
Anyhow, when asked to write those on a blackboard, I typically do this:
andYup, --j.
Also, the XOR version probably isn't worth the complexity.
True in practice, but on a blackboard during an interview, it obviates the need to recode for the follow-up "now reverse the string in place" request.
You have a bug in strlen:
should be:Right you are. Wrote all those in the comment block. Fixed in an edit.
void strcpy(char s1, char s2) { while((s1++) = (s2++)); }