如何使用指针算法为结构内的数组赋值?
How to assign a value to an array inside a structure using pointer arithmetic?
typedef struct TILE{
char p[4];
char ladder,snake;
char end;
int boardLoc;
struct TILE *pointer;
}tile;
tile *myTable = (tile*) calloc(row*col,sizeof(tile));
//This code works (using brackets [])
(myTable+90)->p[0] = 'a';
(myTable+90)->p[1] = 'b';
(myTable+90)->p[2] = 'c';
(myTable+90)->p[3] = 'd';
//This code does not work (using pointer arithmetic)
*(myTable+90).(*(p+0)) = 'a';
*(myTable+90).(*(p+1)) = 'b';
*(myTable+90).(*(p+2)) = 'c';
*(myTable+90).(*(p+3)) = 'd';
//This code does not work either (arrow operator and pointer arithmetic to access array)
(myTable+90)->(*(p+0)) = 'a';
(myTable+90)->(*(p+1)) = 'b';
(myTable+90)->(*(p+2)) = 'c';
(myTable+90)->(*(p+3)) = 'd';
我们在编写代码时需要使用指针运算。我很难弄清楚如何仅使用指针算术方法为包装在结构中的数组赋值。还有另一种方法可以解决这个问题吗?谢谢!
以下都是等价的:
myTable[90].p[3] = 'd';
*(myTable[90].p+3) = 'd';
(myTable+90)->p[3] = 'd';
*((myTable+90)->p+3) = 'd';
(*(myTable+90)).p[3] = 'd';
*((*(myTable+90)).p+3) = 'd';
第一种形式仅使用数组索引运算符[]
。最后一种形式仅使用指针添加和取消引用。
typedef struct TILE{
char p[4];
char ladder,snake;
char end;
int boardLoc;
struct TILE *pointer;
}tile;
tile *myTable = (tile*) calloc(row*col,sizeof(tile));
//This code works (using brackets [])
(myTable+90)->p[0] = 'a';
(myTable+90)->p[1] = 'b';
(myTable+90)->p[2] = 'c';
(myTable+90)->p[3] = 'd';
//This code does not work (using pointer arithmetic)
*(myTable+90).(*(p+0)) = 'a';
*(myTable+90).(*(p+1)) = 'b';
*(myTable+90).(*(p+2)) = 'c';
*(myTable+90).(*(p+3)) = 'd';
//This code does not work either (arrow operator and pointer arithmetic to access array)
(myTable+90)->(*(p+0)) = 'a';
(myTable+90)->(*(p+1)) = 'b';
(myTable+90)->(*(p+2)) = 'c';
(myTable+90)->(*(p+3)) = 'd';
我们在编写代码时需要使用指针运算。我很难弄清楚如何仅使用指针算术方法为包装在结构中的数组赋值。还有另一种方法可以解决这个问题吗?谢谢!
以下都是等价的:
myTable[90].p[3] = 'd';
*(myTable[90].p+3) = 'd';
(myTable+90)->p[3] = 'd';
*((myTable+90)->p+3) = 'd';
(*(myTable+90)).p[3] = 'd';
*((*(myTable+90)).p+3) = 'd';
第一种形式仅使用数组索引运算符[]
。最后一种形式仅使用指针添加和取消引用。