This is the mail archive of the
gdb@sourceware.org
mailing list for the GDB project.
Re: printing array in function
- From: Steffen Dettmer <steffen dot dettmer at googlemail dot com>
- To: gdb at sourceware dot org
- Date: Fri, 3 Sep 2010 12:24:00 +0200
- Subject: Re: printing array in function
- References: <4C80BA7A.3030309@lip6.fr>
On Fri, Sep 3, 2010, Nicolas Sabouret <Nicolas.Sabouret@lip6.fr> wrote:
> The problem we have is that arrays passed to functions are seen as
> pointers by gdb. Here is a simple example :
>
> 1: ?void f(int tab[]) {
> 5: ? ?int t[] = {-1,-1};
>
> (gdb) p tab ? ? -> (int *) 0xbffff440
I think this is absolutely correct.
tab is an int pointer, the storage size of a referenced "array" isn't known.
> The only solution we found to display tab as an array is to use "p
> *tab@2", but this requires knowing the exact size of the array (2 in
> this example).
Yes, absolutely, same as in C:
------------------------------------------------------------------->8=======
#include <stdio.h>
void f(int tab[]) {
tab[0] = 1;
/* (%z is not known to all compilers) */
printf("sizeof(tab) = %lu\n", (unsigned long)sizeof(tab));
}
int main() {
int t[] = {-1,-1};
printf("sizeof(t) = %lu\n", (unsigned long)sizeof(t));
f(t);
return 0;
}
=======8<-------------------------------------------------------------------
produces
sizeof(t) = 8
sizeof(tab) = 4
so function f() also needs to know the size or number of
elements, even when a "size" is given:
void f(int tab[2]) {
assert(sizeof(tab) == sizeof(int*));
}
to illustrate this, development rules may forbid array notation
for function notation instead of pointer, leading to:
void f(int *tab) {
tab[0] = 1;
}
which, as far as I know, the same as above and should be portable.
> Our problem is that the gdb calls are integrated in a front-end for
> students (they do not type gdb commands directly) and that our frontend
> has no way of "guessing" what is the correct size for the array.
maybe by passing a size parameter (which is usually needed anyway
to be able to know the size of the array):
void f(int *tab, size_t tab_size) {
tab[0] = 1;
}
{
int t[] = {-1,-1};
f(t, sizeof(t)/sizeof(t[0]));
}
and using tab_size in the frontend?
oki,
Steffen