Live data from Hacker News

Ask HN: Favorite pointer tricks in C?

news.ycombinator.com

1–10 of 81 posts

Ask HN: Favorite pointer tricks in C?

#1
Hey HN,

I'm teaching a class to a bunch of high school and middle school students tomorrow who've all had moderate experience with programming. I'm covering pointer basics in C as a light intro or refresher, then focusing on cool (but relatively simple / not too crazy) tricks/tips/etc (e.g. stack walking, function pointer arrays). Care to share any of your favorite small pointer tricks with me for the class?

Thanks :)

-Cam

Re: Ask HN: Favorite pointer tricks in C?

#5
What I think takes the cake is this:

  array[index] == index[array]
Not that you would actually use this, but it gave me a lot of insight into how addressing and stuff works inside the compiler. Also from this example, there's the implicit suggestion that an array can be treated as a pointer. So that leads into pointer arithmetic which can be very useful.

Re: Ask HN: Favorite pointer tricks in C?

#6
You can demonstrate pointer arithmetic by showing how you would work with the strstr function. It's the clearest and most understandable reason for someone to see why you'd even discuss this topic I think. I talk to some people without C experience and they hear that idea and get scared. I usually explain how strstr works and that seems to always make sense to them.

Good luck!

Re: Ask HN: Favorite pointer tricks in C?

#7
post #3

implementing linked lists the way the linux kernel does, that is: each node contains one pointer for each list it can be part of, that pointer's position is determined using some offset_of( field, name) macro.

I've recently started using offsetof in my own code, it's a pretty neat operator. Useful for nested structs, where you have a child but need to reference the parent.

Re: Ask HN: Favorite pointer tricks in C?

#9
One that comes to mind:

    struct name {
      int namelen;
      char namestr[1];
    };
    struct name *makename(char *newname)
    {
      struct name *ret =
      malloc(sizeof(struct name)-1 + strlen(newname)+1);
          /* -1 for initial [1]; +1 for \0 */
      if(ret != NULL) {
        ret->namelen = strlen(newname);
        strcpy(ret->namestr, newname);
      }
      return ret;
    }
(From http://c-faq.com/struct/structhack.html ) Simple way of storing a string's name and length in one allocated structure.

Others: virtual function tables, function pointers inside of structs that take a "this" argument effectively giving you OOP, opaque pointers to give compile- and run-time private encapsulation...

Post reply on HN