Re: Printing a 2D array in a C program

Pedro Alves
2016-03-04T18:24:24Z

On 03/04/2016 05:48 PM, Jan Kratochvil wrote:
> The bug with the parameter:
> (gdb) s
> p (m=0x7fffffffd2a0, n=1) at matrix2.c:9
> (gdb) ptype m
> type = int (*)[17]
> (gdb) p m
> $2 = (int (*)[17]) 0x7fffffffd2a0
> (gdb) p *m
> $3 = {-134241616, 32767, -134252848, 32767, -140382932, 32767, 2224, 0, -134252032, 32767, -136422399, 32767, 2224, 0, -140329216,
> 32767, -134252112}

It's a C gotcha, but I don't think it's a bug. Essentially, a parameter
declared as an array is really treated as a pointer parameter.

From http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf:

"
6.7.5.3 Function declarators (including prototypes)
Constraints
(...)

7

A declaration of a parameter as Â‘Â‘array of typeÂ’Â’ shall be adjusted to Â‘Â‘qualified pointer to typeÂ’Â’ (...)
"

So the DWARF describes the type as really what is is. See:

~~~~~~~~~~~~~~~~
$ cat array-param.c
#include <stdlib.h>
#include <stdio.h>

enum
{
sz = 17
};

void
p (int m[sz][sz])
{
printf ("m: sizeof m = %d\n", (int) sizeof (m));
}

void
f (void)
{
int m[sz][sz];

printf ("f: sizeof m = %d\n", (int) sizeof (m));

p (m);
}

int
main ()
{
f ();
return 0;
}

$ gcc -v
gcc version 6.0.0 20160301 (experimental) (GCC)
$ gcc array-param.c -o array-param -Wall -Wextra -O2
array-param.c: In function Â‘pÂ’:
array-param.c:12:46: warning: Â‘sizeofÂ’ on array function parameter Â‘mÂ’ will return size of Â‘int (*)[17]Â’ [-Wsizeof-array-argument]
printf ("m: sizeof m = %d\n", (int) sizeof (m));
^
array-param.c:10:8: note: declared here
p (int m[sz][sz])
^
$ ./array-param
f: sizeof m = 1156
m: sizeof m = 8
~~~~~~~~~~~~~~~~

Thanks,
Pedro Alves