23

I am declaring a two dimensional array as such:

char arr[10][10];
arr[0][0] = 'X';

Now I print in debugger;

(lldb) po arr[0][0]
'X'

Awesome!! No problem.

Now I am declaring a two dimensional array as such:

int col = 10;
int row = 10;
char arr[row][col];
arr[0][0] = 'X';

Now I print in debugger;

(lldb) po arr[0][0]
error: subscript of pointer to incomplete type 'char []'
error: 1 errors parsing expression

Why??

dbush
  • 205,898
  • 23
  • 218
  • 273
etayluz
  • 15,920
  • 23
  • 106
  • 151
  • 1
    I suppose that neither DWARF nor gdb support variable length arrays. – fuz Jan 22 '16 at 16:51
  • 2
    `double array as such:` means? – Sourav Ghosh Jan 22 '16 at 16:52
  • 3
    @SouravGhosh "A two-dimensional array like this:" was my interpretation. Quite confusing since `double` makes you think of floats. – unwind Jan 22 '16 at 16:53
  • 2
    Note that the debugger has no clue on the dimension of the array, so you have to manually cast and dereference it. The debugger will works as you expect if you declare both *row* and *col* as *const*. ` (gdb) print arr[0][0] $2 = 88 'X' ` – Davide Spataro Jan 22 '16 at 17:06

3 Answers3

18

The debugger doesn't know exactly how big the array is, so you need to apply a cast:

(gdb) p ((char (*)[10])arr)[0][0]
$2 = 88 'X'
dbush
  • 205,898
  • 23
  • 218
  • 273
15

So dbush is right. But here's why in a little more depth.

char arr[10][10];

isn't the same thing as

char arr[row][col];

Even though they look and act similar.

In the C89 standard, the second would be illegal as the compiler has no idea how much space to allocate for the variable (even though that's defined in the previous two lines).

Enter the C99 standard and they introduced something called variable length arrays. The space allocation for the array is determined at runtime rather then at compile-time. Now you can pass in a couple of variables to a function and declare an array with a size based on those variables. Yay!

But it means the compiler officially doesn't know details about the array. Like how big it is. And LLDB uses the Clang/LLVM compiler to make sense of the code.

It's an example of the language becoming slightly higher level and abstracting the work it does under the hood. And occasionally that bites you in the ass.

dbush
  • 205,898
  • 23
  • 218
  • 273
Philip
  • 1,539
  • 14
  • 23
2

make the col and row const

const int col = 10; const int row = 10;

Liu Hao
  • 472
  • 4
  • 24
  • This is a C language question. In C making them `const` will not make a difference. In C language `const` on `col` and `row` will not prevent the array from becoming VLA and thus will have no effect of the original issue. – AnT stands with Russia Apr 13 '16 at 00:01