Skip to content

Comment on Ask HN: Favorite pointer tricks in C?

Comments

Instead 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;
    }

Shouldn'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;
    }

Yup, --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:

     for(cur=str; cur; ++cur);
should be:
     for(cur=str; *cur; ++cur);

Right you are. Wrote all those in the comment block. Fixed in an edit.

   size_t strlen(char *s)
   {
     size_t i = 0;
     while(*s++) i++;
     return i;
   }

void strcpy(char s1, char s2) { while((s1++) = (s2++)); }

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.