4 ms·
First up, this is just invalid in C++, because C++'s type system has a bunch of the foot guns removed from it. In C this will probably work, but only because V
by olliej 4y ago
First up, this is just invalid in C++, because C++'s type system has a bunch of the foot guns removed from it.
In C this will probably work, but only because VLAs in C are broken by design - VLAs are not part of the type system, which means there is no actual required relationship between the size of the array - even when statically known as in your example - and the parameters to the function. So yes your example will print 3, but that's because it will print whatever you pass in for x. So I can equally do:
foo(500, &a);
and that's valid, and I would put money on not producing even a warning. Again because VLAs aren't part of the type system I could also do:
foo(5, malloc(1));
and that should work fine as well, because VLAs are again not real.
Moreover this is also kind of missing the point: I said there is no way to distinguish a pointer from an array allocation, and your example is not using a pointer or an array, it is using a pointer and an additional length value - and yes, the correct thing to do is to have a struct containing both of those, or probably better a struct with trailing storage. Either way the C or C++ type system does not distinguish between a pointer to an object, or a pointer to an array of N (including potentially 1) objects, and you, the programmer need to do this yourself without language support.