我在 stackoverflow 上快速搜索后发布了这个...
我在从 GDB 打印 VLA 条目时遇到了问题,这是我简化的 C 代码片段。
#include <stdio.h>
#include <stdlib.h>
typedef struct
{ int i, j;
} c_t;
int f(int l, int c, c_t a[l][c])
{ for(int i=0;i<l;i++)
{ for(int j=0;j<c;j++)
{ a[i][j].i=i; a[i][j].j=j;
}
}
}
int main(int ac, char **av)
{ int l=(int)atoi(av[1]), c=(int)atoi(av[2]);
c_t a[l][c];
return(f(l,c,a));
}
我编译它
$ cc -o g g.c -g -O0
然后在其上运行 GDB,在 f() 中进行几次迭代后,我尝试显示 a[i][j]
$ gdb ./g
GNU gdb (Ubuntu 8.1-0ubuntu3) 8.1.0.20180409-git
...[snip]...
Reading symbols from ./g...done.
(gdb) r 2 3
Breakpoint 1 at 0x76b: file g.c, line 17.
Breakpoint 1, main (ac=3, av=0x7fffffffe608) at g.c:17
17 { int l=(int)atoi(av[1]), c=(int)atoi(av[2]);
(gdb) n
18 c_t a[l][c];
(gdb)
19 return(f(l,c,a));
(gdb) s
f (l=2, c=3, a=0x7fffffffe440) at g.c:8
8 int f(int l, int c, c_t a[l][c])
(gdb) n
9 { for(int i=0;i<l;i++)
(gdb)
10 { for(int j=0;j<c;j++)
(gdb)
11 { a[i][j].i=i; a[i][j].j=j;
(gdb)
10 { for(int j=0;j<c;j++)
(gdb)
11 { a[i][j].i=i; a[i][j].j=j;
(gdb)
10 { for(int j=0;j<c;j++)
(gdb)
11 { a[i][j].i=i; a[i][j].j=j;
(gdb)
10 { for(int j=0;j<c;j++)
(gdb)
9 { for(int i=0;i<l;i++)
(gdb) p a[0][0]
Cannot perform pointer math on incomplete types, try casting to a known type, or void *.
(gdb)
从那里我被困住了,尝试了各种 Actor 都没有成功。
提前感谢任何指针(可能指针比数组更好:))
披
最佳答案
应该始终有效的,实际上是指针运算。
您可以使用类似以下的命令:
(gdb) p *((c_t*)a+0*3+0)
$3 = {i = 0, j = 0}
(gdb) p *((c_t*)a+0*3+1)
$4 = {i = 0, j = 1}
(gdb) p *((c_t*)a+0*3+2)
$5 = {i = 0, j = 2}
(gdb) p *((c_t*)a+1*3+0)
$6 = {i = 1, j = 0}
(gdb) p *((c_t*)a+1*3+1)
$7 = {i = 1, j = 1}
(gdb) p *((c_t*)a+1*3+2)
$8 = {i = 1, j = 2}
顺便说一句:与您的问题无关:f
的函数签名指定类型为 int
的返回值,但不返回任何内容。
关于c - GDB C 如何打印 VLA 条目(动态数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57434081/