Quite right. I use, and highly recommend, the convention that `size` is for number of bytes, `length` is for number of elements, and `capacity` for the allocated number of elements.
assert(length * sizeof(element) == size);
assert(length <= capacity);I don't code c full time, but it's what I have always done when needing to use c via ffi to get a speed up in a dynamic language.
the problem with this approach is that you are still relying on the application programmer to provide the correct size at the beginning and not to mess it up by directly accessing the struct member later. private/public does not really exist in c, so it is a lot harder to enforce invariants within an object. the library could make the struct layout a private implementation detail (ie, not fully define the struct in the header provided to the client and take a pointer to the struct as arguments in the API) to at least discourage this. you could combine this approach with a my_array_struct_init function that returns a pointer to an empty array object. this is a common approach taken in c libraries (eg, libcurl) where the author really doesn't want you messing with their structs.
- Statically check the code, since the static analysis tool knows for certain which value is the size and can check that you're using correctly.
- Initialize the size correctly, since you don't have to enter it twice, or more crucially, remember to change it twice (or create a #define in another part of the file, name it, and document it)
You also make an excellent point yourself about the meaning of 'size'. If this was standardized, it would be the same everywhere, minimizing the risk of ambiguity.
I don't interpret Walter's suggestion that way. Of course, I might be wrong. Since the compiler must know the size of the array at the time it's declared, my thinking is that the compiler is smart enough to pass the size without the programmer having to even think about it.
unless you have a team of incredibly diligent coders, people are going to read past the end of bare arrays over and over again. one specific mistake I keep seeing is where people misinterpret the meaning of a variable named `size`. is it the number of elements or the size in bytes? who knows, but it's probably UB either way if you're wrong.