我正在努力讓一個結構指向另一個依賴於傳入命令行的參數,問題是,結構我看起來正在指向所需的初始化結構但是,當我在函數調用後打印它們的地址時,在main中,如果播放器是A,則它看起來沒有改變(在輸出之後):指向一個結構到另一個? (不是永久性的)
Before initialise: 0x7f8a88403990, 0x7f8a884039f0, 0x7f8a88403a50, 0x7f8a88403ab0, 0x7f8a88403b10
After initialise: 0x7f8a884039f0, 0x7f8a884039f0, 0x7f8a88403a50, 0x7f8a88403ab0, 0x7f8a88403b10
After parse args: 0x7f8a88403990, 0x7f8a884039f0, 0x7f8a88403a50, 0x7f8a88403ab0, 0x7f8a88403b10
int main (int argc, char *argv[]) {
Player *me = NULL, *playerA = NULL;
Player *playerB = NULL, *playerC = NULL, *playerD = NULL;
me = malloc(sizeof(*me));
playerA = malloc(sizeof(*playerA));
playerB = malloc(sizeof(*playerB));
playerC = malloc(sizeof(*playerC));
playerD = malloc(sizeof(*playerD));
parse_args(me, playerA, playerB, playerC, playerD, argv);
//should be pointing to the same memory location
printf("After parse args: %p, %p, %p, %p, %p\n", me, playerA, playerB, playerC, playerD);
}
void parse_args(Player *me, Player *a, Player *b, Player *c, Player *d,
char *argv[]) {
initialise_game(*tempChar, tempNum, me, a, b, c, d);
}
void initialise_game(char playerID, int numPlayers, Player *me, Player *a,
Player *b, Player *c, Player *d) {
printf("Before initialise: %p, %p, %p, %p, %p\n", me, a, b, c, d);
switch((int)playerID) {
case 'A':
me = a;
break;
case 'B':
me = b;
break;
case 'C':
if (numPlayers < 3) {
exit_prog(EXIT_PLAYERID);
}
me = c;
break;
case 'D':
if (numPlayers < 4) {
exit_prog(EXIT_PLAYERID);
}
me = d;
break;
}
printf("After initialise: %p, %p, %p, %p, %p\n", me, a, b, c, d);
}
謝謝你提供了一個明確的答案,我現在明白了這項工作是如何的(對不起,我的頭腦有些棘手) – user3603183 2014-09-25 22:50:25
通過價值傳遞指針並嘗試修改它們是棘手的 - 它捕捉到許多新的C程序員未料到。我鏈接到的Stackoverflow問題可以幫助你非常。但是如果你想修改一個函數中的指針,你需要傳遞它的地址,然後在函數中去引用來完成賦值 – 2014-09-25 22:54:08