4 ms·
I would agree. IMO, I would argue that if you are in that situation, you should just wrap the array in a `struct`. It will work the same way, but now nobody can
by DSMan195276 8y ago
I would agree. IMO, I would argue that if you are in that situation, you should just wrap the array in a `struct`. It will work the same way, but now nobody can get the size wrong - the `struct` will always have an array of the correct length inside it. And as a bonus you can give it a good name.
- 0x09 8y agoI 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.
- j1elo 8y agoThis 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.
- 1over137 8y agoBut remember structure padding, which the compiler is free to add in the middle (and end) of a struct (though there are pragmas and/or attributes to pack structs). IOW, an array and a struct are not necessarily the same in memory.
- rocqua 8y agoThe array in a struct is still going to be continuous in memory. All you might change is allignment.
- DSMan195276 8y agoThat's completely true, however in practice any extra padding shouldn't matter unless you're trying to do some funny buisness or are severly memory constrained. If all you really needed was a fixed-sized array, then it should work exactly the same, even if it technically uses a byte or two more. (Edit: And of course, while I think you already know this, the compiler can't add padding inside the array, so the array it self will still be exactly the same memory-wise). With that, I wouldn't expect that any padding would be added since the array should already have the same alignment as the `struct` anyway - but compilers are known to do weird things from time to time, so it's definitely not impossible.