C++ Logo

std-proposals

Advanced search

Re: Pointers to VLAs as in C99 - (was: Arrays (VLAs) as function parameters (as in C99))

From: Alejandro Colomar (man-pages) <"Alejandro>
Date: Sun, 7 Nov 2021 22:01:12 +0100
On 11/7/21 21:53, Alejandro Colomar (man-pages) wrote:
> In C, in the case of a single-dimension array in a function parameter,
> such as
>
> int foo(int n, int arr[n]);
>
> it is purely syntactic sugar, as `sizeof(arr)` == `sizeof(int*)` and
> *not* `sizeof(int) * n`. And many programmers ignore (or forget) that,
> which has caused recurrent bugs. See my StackOverflow answer which
> covers that in much more detail (the question was "How do I determine
> the size of my array in C?"):
> <https://stackoverflow.com/a/57537491/6872717>.
> That point also suggests that C2X should add _Lengthof ASAP, but that's
> another story.
>
> In the case of multi-dimensional arrays, the size of all except the
ups> outermost array are true arrays; only the outermost array decays to a
> pointer. Therefore, in a case such as
>
> int bar(int l, int m, int n, int md_arr[l][m][n]);
>
> [l] is just syntactic sugar, but [m] and [n] are real dimensions of
> subarrays, and therefore `sizeof(md_arr)` == `sizeof(int) * m * n`.

Oops, I had a serious bug here. The correct would be:

foo():
 sizeof(arr) == sizeof(int *)
 sizeof(arr[0]) == sizeof(int)

bar():
 sizeof(md_arr) == sizeof(int (*)[m][n]) == sizeof(int *)
 sizeof(md_arr[0]) == sizeof(int [m][n]) == sizeof(int) * m * n



-- 
Alejandro Colomar
Linux man-pages comaintainer; https://www.kernel.org/doc/man-pages/
http://www.alejandro-colomar.es/

Received on 2021-11-07 15:01:17