首页 > 解决方案 > 如何使用指针算法为结构内的数组赋值?

问题描述

 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';

我们需要在编写代码时使用指针算法。我很难弄清楚如何仅使用指针算术方法将值分配给包装在结构内的数组。还有其他方法可以解决这个问题吗?谢谢!

标签: cpointersinitializationstructurepointer-arithmetic

解决方案


以下都是等价的:

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';

第一种形式仅使用数组索引运算符[]。最后一种形式仅使用指针添加和取消引用。


推荐阅读