I'm trying to implement a coordinate system for a player in a game.
I have a struct
typedef struct player {
int playerPosition[1][5];
}
I create a pointer to that struct
struct* player playerPtr;
struct player playerOne;
playerPtr = &playerOne;
If during the game, I want to update the coordinate of the player to position [1,2].
I get errors when I use playerPtr->playerPosition=[1][2]
;
What's the correct way of doing this?
As written, you could do this:
playerPtr->playerPosition[0][2] = 100;
But probably you have an error here:
int playerPosition[1][5];
Because it rarely makes sense to have an array of size 1. Did you really mean for playerPosition
to be a 1x5 array of ints? It looks like you wanted something like this:
struct position {
int x, y;
};
struct player {
position playerPosition;
};
Then you would do this:
playerPtr->playerPosition.x = 1;
playerPtr->playerPosition.y = 2;
playerPtr->playerPosition=[1][2];
will give you error (syntactically wrong)
you are not specifying the array index at which the data is to be stored, also you cant store data by that way in C
.
correct way would be:
playerPtr->playerPosition[0][0] = 1;
playerPtr->playerPosition[0][1] = 2;
.
.
.
playerPtr->playerPosition[9][0] = 19;
playerPtr->playerPosition[9][1] = 20;
which is valid if you declare your array like this:
int playerPosition[10][2];
which will allow you to store ten coordinates.
2Dimentional arrays such as array[1][10] are same as array[10] (for usage, I am not certain about memory allocation, 2D array might require more memory)
I think you could use different but easier approach to this problem:
typedef struct position{
int x, y;
float refpos; //position from some reference point (like healing circle)
}position;
typedef struct player{
char name[20];
int health, attack, defense; //can be float too
position coord[20];
}player;
player player1, *playerPtr;
playerPtr = &player1;
playerPtr->position[0].x = 3;
playerPtr->position[0].y = 4;
playerPtr->position[0].refpos = 5; //Pythagorean triplet wrt origin (0,0)
Prost !
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.