News for hackers. Stuff that matters.
Re:Ask HN: Favorite pointer tricks in C? by Jach on Saturday November 20, 2010 @05:24PM (#1925526)
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...

Re:Ask HN: Favorite pointer tricks in C? by bbulkow on Saturday November 20, 2010 @08:00PM (#1925856)
The correct way to write this is to not use /1/ in the size of namestr, it's to use a simple []. This tells subsequent programmers that you are using variable length structures. In older compilers, the metaphor was to use '0', but C99 (maybe even earlier) got everyone using [].

Here's a nice discussion in StackOverflow, including a bunch of C++ guys saying to just use Vectors, which ignores the entire point of getting a structure with only one memory allocation:

http://stackoverflow.com/questions/688471/variable-sized-str...

Re:Ask HN: Favorite pointer tricks in C? by Jach on Sunday November 21, 2010 @05:31PM (#1928075)
From GCC: ISO C90 does not support flexible array members. and: ISO C forbids zero-size array 'namestr'

Therefore I contest that your way is the "correct" way, especially since most C code is not C99 code. Also I'd probably never use this in C++. If you want to let subsequent programmers know you're using the variable length structure, add the comment: /* unwarranted chumminess with the compiler */