[英]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';
We are required to use pointer arithmetic in writing our code.我们需要在编写代码时使用指针算法。 I am having a hard time figuring out how to assign a value to an array which is wrapped inside a structure with just utilizing pointer arithmetic method.
我很难弄清楚如何仅使用指针算术方法将值分配给包装在结构内的数组。 Is there another way to go through this?
go 还有其他方法吗? Thanks!
谢谢!
The following are all equivalent:以下都是等价的:
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';
The first form uses only the array indexing operator []
.第一种形式仅使用数组索引运算符
[]
。 The last form uses only pointer addition and dereferences.最后一种形式仅使用指针添加和取消引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.