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? 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.