4 ms·
Would you just wrap the pointer and size in a strut, then only iterate the array via a library of functions that check the size first? I don't code c full time
by true_religion 6y ago
Would you just wrap the pointer and size in a strut, then only iterate the array via a library of functions that check the size first?
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.
- leetcrew 6y agoyou could do that, if you were using a library that provided/understood that struct. not sure how common this is; I work with c++ much more than c. 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.
- WalterBright 6y agoYou can, but since C doesn't have templates or operator overloading this becomes awkward and unappealing.