Reputation: 23
when I use gdb to debug my code, I meet a problem which makes me headache, here is my code snippet:
int getMaxProfits( int *boards, int length, int consecutive )
{
int optBoards[length+3][length+3];
memset(optBoards, 0, sizeof( optBoards ) );
for( int i = length -1; i >= 0; i-- )
{
for( int j = i; j <= length - 1; j++ )
{
if( j == i )
{
optBoards[i][j] = boards[j];
}
else if( j - i < consecutive )
{
optBoards[i][j] = boards[j] + optBoards[i][j-1];
}
.....
when I tried to print out all the elements in 2-dimensional array "optBoards" by
p optBoards
I found the thing is not as easy as I thought, it gives me
$1 = 0x7fff5fbff330
looks like a memory address, then I tried
p optBoards[0][0]
I got
Cannot perform pointer math on incomplete types, try casting to a known type, or void *.
I keep trying
ptype optBoards
I saw
type = int [][0]
I wildly guess optBoards should be a pointer points to a one-dimension array, hence I tried again
p (int[][0])(*optBoards)[0]
I got a memory address again
$2 = 0x7fff5fbff330
I saw some hope and tried again
p (int[][0])*((*optBoards)[0])
now I get a big 0
$3 = 0x0
I thought I already got the value I want, later I found out after I entering the for loop, optBoards would be assign some value, but no matter what, I always got a big 0 for all the elements of optBoards. I feel lost.
what should I do to print out the correct value for this 2-dimension array?
your help would be greatly appreciated.
Upvotes: 2
Views: 4898
Reputation:
You can do it as p ((int (*)[8]) optBoards)[6][2]
, whereas 8
is length + 3
. For example I have:
#pragma GCC diagnostic ignored "-Wunused-variable"
#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
#include <stdio.h>
int foo(int length) {
int optBoards[length + 3][length + 3];
int i, j, q;
for( i = 0, q = 0 ; i < length + 3 ; i++ ) {
for( j = 0 ; j < length + 3 ; j++ ) {
optBoards[i][j] = ++q;
printf("optBoards[%d][%d] = %d\n", i, j, q);
}
}
return 0;
}
int main(int argc, char **argv) {
foo(5);
return 0;
}
you can check the array data as:
> gcc -Wall file.c -g -o file.exe
> gdb -q file.exe
Reading symbols from file.exe...done.
(gdb) l 18
13 optBoards[i][j] = ++q;
14 printf("optBoards[%d][%d] = %d\n", i, j, q);
15 }
16 }
17
18 return 0;
19 }
20
21 int main(int argc, char **argv) {
22
(gdb) b 18
Breakpoint 1 at 0x4017eb: file file.c, line 18.
(gdb) run
Starting program: file.exe
[New Thread 2912.0xad8]
optBoards[0][0] = 1
...
optBoards[1][2] = 11
...
optBoards[2][7] = 24
...
optBoards[6][2] = 51
...
optBoards[7][7] = 64
Breakpoint 1, foo (length=5) at file.c:18
18 return 0;
(gdb) p length + 3
$1 = 8
(gdb) p ((int (*)[8]) optBoards)[0][0]
$2 = 1
(gdb) p ((int (*)[8]) optBoards)[1][2]
$3 = 11
(gdb) p ((int (*)[8]) optBoards)[2][7]
$4 = 24
(gdb) p ((int (*)[8]) optBoards)[6][2]
$5 = 51
(gdb) p ((int (*)[8]) optBoards)[7][7]
$6 = 64
(gdb)
Upvotes: 3