3 ms·
I don't entirely agree with this article ... it's quite possible to "pass" an array as a pointer to an array type, as opposed to a decayed pointer, e.g. void
by tpoacher 3y ago
I don't entirely agree with this article ... it's quite possible to "pass" an array as a pointer to an array type, as opposed to a decayed pointer, e.g.
void f( int (*a) [5] );
int a[5] = {1, 2, 3, 4, 5};
f( &a );
The larger problem here is more that this mechanism doesn't support arbitrary sizes. Which probably makes sense from how c handles memory, but it's very restrictive.
Incidentally, I recently had an argument with a friend who had been "coding for years" in c, that the memory address of "a" and "&a" in the example above are identical. He thought it was so obvious I was wrong (because pointers) that I had to code it and print the addresses for him and prove they're the same. He was completely mind-blown xD
- david2ndaccount 3y agoYou can’t pass an array by value and you can’t pass a pointer with a corresponding length of non-fixed size (you can actually with VLAs, but frankly the syntax sucks and not all compilers support it). This missing language feature has led to horrible things like nil-terminated strings , a million bespoke ways to encode the length of the array, or just functions that pray you have enough space like `strcpy` and `gets`.
- tpoacher 3y ago> You can't pass an array by value Sure, but, this is the case in all languages, no? Otherwise, what should be the convention? A deep copy? A first-degree shallow copy? You simply can't avoid the referential nature of arrays for use as arguments to functions. So the issue here shouldn't be the referential nature of this, but the fact that they chose to implement it as a "decaying" pointer as opposed to a "pointer to array type of a certain size". And hence why I'm pointing out there is, in fact, a (relatively simple) way to do this, but only for fixed sizes. But the reason it's not THAT useful in practice is because, in general, you probably wouldn't want the function's parameter to expect a fixed size array, but you'd probably want the flexibility of a variable-sized array, whose length is defined at runtime. And this is what is not supported by c. So in some sense, in the absence of support for variable-sized array parameters, then not expecting fixed array sizes at the point of defining function parameters, and using a decaying pointer instead (which simply doesn't care about the size), is probably the lesser evil of the two. So for me the 'bigger' evil isn't decaying pointers, but the lack of support for VLAs as function parameters. This would have allowed you to use the above syntax to pass a pointer to an array type, retaining full information about the pointed array, including its size. (in other words I think we're saying a very similar thing but with different words)