Re: Printing a 2D array in a C program

Pedro Alves <[email protected]>
Newsgroups gmane.comp.gdb.devel
Message-ID <[email protected]>
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
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.