2017-09-23 106 views
0

我試圖在遊戲中實現一個玩家的座標系。使用指針更新結構中的二維整數數組

我有一個結構

typedef struct player { 
    int playerPosition[1][5]; 
} 

我創建一個指向結構

struct* player playerPtr; 
struct player playerOne; 
playerPtr = &playerOne; 

如果在比賽過程中,我想更新播放器的座標來定位[1,2] 。

我在使用playerPtr->playerPosition=[1][2]時出錯;

這樣做的正確方法是什麼?

+0

'struct player playerOne;結構播放器* playerPtr =&playerOne;'''playerPtr-> playerPosition [1 -1] [2 -1] = intValue;' – BLUEPIXY

+0

你究竟期待這個'playerPtr-> playerPosition = [1] [2];'去做? – alk

+0

關於:'struct * player playerPtr;'應該是:'struct player * playerPtr;' – user3629249

回答

0

書面,你可以這樣做:

playerPtr->playerPosition[0][2] = 100; 

,不過也許你在這裏有一個錯誤:

int playerPosition[1][5]; 

因爲它很少很有意義的尺寸1的陣列你真的意思是playerPosition是一個1x5的整數數組?它看起來像你想是這樣的:

struct position { 
    int x, y; 
}; 

struct player { 
    position playerPosition; 
}; 

然後你可以這樣做:

playerPtr->playerPosition.x = 1; 
playerPtr->playerPosition.y = 2; 
0

playerPtr->playerPosition=[1][2];會給你錯誤(語法錯誤)

你是不是在指定數組索引哪些數據將被存儲,也不能以這種方式在C中存儲數據。

正確的方法是:

playerPtr->playerPosition[0][0] = 1; 
playerPtr->playerPosition[0][1] = 2; 
. 
. 
. 
playerPtr->playerPosition[9][0] = 19; 
playerPtr->playerPosition[9][1] = 20; 

,如果你宣佈你的陣列這樣有效期:

int playerPosition[10][2]; 

,這將允許你存儲十個座標。

2Dimentional陣列如陣列[1] [10]是一樣的陣列[10](供使用,我不能確定的內存分配,二維數組,可能需要更多的內存)

我想你可以使用不同但更容易處理此問題:

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!