News for hackers. Stuff that matters.
Re:C Craft by jgrahamc on Friday December 18, 2009 @10:58AM (#1003298)
I noticed that too, and what's weird is that's not at all how you should do it. Since the char c[0] has zero size you can do sizeof on the struct so that you can do the malloc correctly.

  struct thing {
    int n;
    char c[0];
  };

  int i_need = 16;
  struct thing * foo = malloc(sizeof(struct thing)+i_need);
  foo->n = i_need;

  for (int i = 0; i < foo->n; i++ ) {
    foo->c[i] = 'a' + i;
  }
And if your compiler won't let you do char c[0] you can do char c[1] and either blow a byte, or do the calculation correctly. Note that you have to be careful with this sort of allocation if you are on a machine that has certain alignment requirements (e.g. Sun).
Re:C Craft by cpr on Friday December 18, 2009 @01:43PM (#1003660)
Well, being pedantic, that should be

  struct thing *foo = malloc(sizeof(struct thing) + sizeof(char) * i_need);
since sizeof(char) isn't guaranteed to be 1 byte on all systems.
Re:C Craft by pavlov on Friday December 18, 2009 @02:06PM (#1003714)
Actually, the C standard guarantees that char is equal to one byte.
Re:C Craft by neild on Friday December 18, 2009 @02:18PM (#1003741)
More to the point, it defines a byte in terms of a char. sizeof(char) will always be 1, but UCHAR_MAX need not be 255.