简体   繁体   English

使用指针更新结构中的2d整数数组

[英]Updating a 2d integer array in a struct with a pointer

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]. 如果在游戏期间,我想将玩家的坐标更新为位置[1,2]。

I get errors when I use playerPtr->playerPosition=[1][2] ; 使用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? 因为具有大小为1的数组很少有意义。您真的是说将playerPosition的整数数组吗? 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 . 您没有指定要在其中存储数据的数组索引,也无法通过这种方式在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) 2维数组,例如array [1] [10]与array [10]相同(就用法而言,我不确定内存分配,二维数组可能需要更多内存)

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 ! 普罗斯特!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM