2015-09-28 81 views
0

我在C中遇到了一個奇怪的問題,我正在使用一個結構體。其中一個結構元素是一個大小爲3的char數組的數組。該元素意味着是玩家的手,並且char數組意味着成爲單個卡。他們格式化爲「2C」,其中2是排名,C是俱樂部。我的問題在於從給定的字符串創建玩家手的功能。在循環中,j是卡片索引,最後它將創建的卡片(我知道是正確的)分配給索引。在循環的最後一次迭代中,它分配了4C,並且由於某種原因,每個元素都變爲4C。這裏是該功能的代碼:爲Struct中的指針指向char指針將覆蓋所有值?

typedef struct dataStruct { 
int playerCount; 
int handSize; 
char playerID; 
char** playerHand; 
} dataStruct; 

void proc_new_round(struct dataStruct* data, char* input) { 
int length = strlen(input), i = 9, j = 0; 
char tempChar[3]; 
if (length != 86 && length != 59 && length != 47) 
    invalid_hub_message(); 
else if (input[8] != ' ') 
    invalid_hub_message(); 
alloc_hand_size(data, (length - 8)/3); 
for (j = 0; j < data->handSize; j++) { 
    if (input[i] != '2' && input[i] != '3' && input[i] != '4' && 
     input[i] != '5' && input[i] != '6' && input[i] != '7' && 
     input[i] != '8' && input[i] != '9' && input[i] != 'T' && 
     input[i] != 'J' && input[i] != 'Q' && input[i] != 'K' && 
     input[i] != 'A') { 
     invalid_hub_message(); 
    } 
    tempChar[0] = input[i++]; 
    if (input[i] != 'H' && input[i] != 'D' && input[i] != 'C' && 
     input[i] != 'S') { 
     invalid_hub_message(); 
    } 
    tempChar[1] = input[i++]; 
    tempChar[2] = '\0'; 
    printf("tempchar %s\n", tempChar); 
    data->playerHand[j] = tempChar; 
    if (i < length) { 
     if (input[i++] != ',') 
      invalid_hub_message(); 
    } 
    printf("%d\n", j); 
} 
data->playerHand[5] = "7C"; 
printf("%s\n", data->playerHand[5]); 
printf("%s\n", data->playerHand[12]); 
printf("%s\n", data->playerHand[7]); 
//print_hand(data); 
} 

的函數給出的輸入是: newround 2C,2C,2C,2C,2C,2C,2C,2C,2C,2C,2C,2C,4C 在功能結束時,打印的3張卡片是7C,4C和4C,但考慮到創建的臨時卡片,它應該是7C,4C和2C。我的打印手功能也打印除索引5以外的每張卡片爲4C。有人能告訴我這裏發生了什麼事嗎?

+0

沒有主要功能包括 – amdixon

+0

的代碼是真實相關的功能代碼,我測試的存儲器的分配的手所以不包括在內。 –

+3

因爲我們沒有辦法複製或測試你的代碼 – amdixon

回答

2
data->playerHand[j] = tempChar; 

所有data->playerHand指針具有相同的值和點到同一陣列,tempChar。不管最後寫到tempChar是什麼,都會顯示爲所有的最終值。

您的代碼類似於此:

int *a[4]; 
int tmp; 
int j; 

for (j = 0; j < 4; j++) { 
    tmp = j * 10; 
    a[j] = &tmp; 
} 

int dummy = 42; 
a[1] = &dummy; 

printf("%d %d %d %d\n", *a[0], *a[1], *a[2], *a[3]); 

所有的數組元素被設置由環路指向tmpa[1]然後被覆蓋指向dummy。的tmpdummy的最終值分別爲2042,所以輸出是

20 42 20 20 
+0

好吧,但是當數據 - > playerHand [5] =「7C」時,怎麼會發生進程,並不是所有的值都變成了「7C」? –

+0

@JessAhrens因爲你只是分配給'data-> playerHand [5]'? – melpomene

+0

是的,但它不是在for循環的上下文中與'data-> playerHand [j] = tempChar'相同,因爲j從0增加到handsize,每次迭代都會增加索引不是嗎? –