【发布时间】:2021-04-07 11:06:57
【问题描述】:
我有一个 char 数组的 typedef 来表示棋子的位置。
typedef char chessPos[2];
然而,当我尝试创建这种类型的数组时,我遇到了无法解释的行为。 例如。
chessPos test= {'A','1'};
chessPos test2= {'B','2'};
chessPos* ptr = (chessPos*)(malloc(sizeof(chessPos) * 2));
(*ptr)[0] = test[0];
(*ptr)[1] = test[1];
(*ptr+1)[0] = test2[0];
(*ptr+1)[1] = test2[1];
printf("(%c,%c)",*ptr[0],(*ptr)[1]);
ptr++;
printf("(%c,%c)",*ptr[0],(*ptr)[1]);
我会得到:
(A,B)(2, )
而不是预期的:
(A,1)(B,2)
【问题讨论】:
-
运算符优先级。
*ptr+1首先取消引用,然后添加。 -
OT:我更喜欢更具可读性和抗错误性的
chessPos* ptr = malloc(sizeof *ptr * 2);分配。