我为表创建自定义类型(二维数组):
typedef int table_t[4][2]; // 4 rows, 2 columns
接下来,我声明表和指向表的指针:
table_t a = { {10, 0}, // my table
{20, 0},
{30, 0},
{40, 0} };
table_t *b = &a; // pointer to my table
接下来,我尝试打印表格的第一列:
printf("%d\n", a[0][0]); // var1.
printf("%d\n", a[1][0]); // It's work
printf("%d\n", a[2][0]);
printf("%d\n", a[3][0]);
它有效。如何通过指向 table_t 的指针访问表中的元素?
我尝试通过指针打印表格的第一列:
printf("%d\n", *b[0][0]); // var2.
printf("%d\n", *b[1][0]); // It's print true value only from *b[0][0] and
printf("%d\n", *b[2][0]); // some strange from other elements
printf("%d\n", *b[3][0]);
也许我做错了什么?突然间,下一个代码对我来说有效,但为什么桌子旋转了? :
printf("%d\n", *b[0][0]); // var3
printf("%d\n", *b[0][1]); // Suddenly, it's work too.
printf("%d\n", *b[0][2]);
printf("%d\n", *b[0][3]);
Godbolt 演示:https://godbolt.org/z/7bb63vGxT
b
具有指向 table_t
的指针类型,因此您应该通过 *b
访问表,并且由于后缀运算符比前缀运算符具有更高的优先级,因此在取消引用表元素之前必须将 *b
添加括号:
printf("%d\n", (*b)[0][0]); // var2.
printf("%d\n", (*b)[1][0]); // It's print true value only from *b[0][0] and
printf("%d\n", (*b)[2][0]); // some strange from other elements
printf("%d\n", (*b)[3][0]);