Hacker News new | ask | show | jobs
by 0x09 2722 days ago
I like using pointer-to-array types for this purpose as (like an array in struct) the array's length is encoded in the type, and thus likewise allows the compiler to warn if an incompatible array is provided. e.g.

   void f(char (*n)[255]);
   char array[6];
   f(&array);
warns of "incompatible pointer types passing 'char (* )[6]' to parameter of type 'char (* )[255]'"

This won't produce a diagnostic for f(NULL) like "static" does, but does have two properties that might be considered benefits:

1) The length is exact rather than a minimum.

2) The type of "* n" is still char[255], whereas a char[static 255] parameter is still a decayed pointer-to-char. Thus with the former sizeof(* n) behaves as expected inside of "f", yielding 255.

These are true of the array-in-struct method as well.

1 comments

This is a fantastic technique that didn't occur to me for an embedded project that I was developing in C and where passing arrays of known size was a frequent thing. Also it was desirable to save space by avoiding the padding that a "array+size" struct would contain.

Thanks for commenting this.