2017-03-09 98 views
0

我正在製作一個關於從第1到第5排序五個團隊的簡單程序..但是我想通過使用傳遞結構方法的指針&指向它。這裏是我做了什麼..傳遞指向結構的指針的數組

#include <stdio.h> 
#include <string.h> 


struct league 
{ 
char team1[20]; 
char team2[20]; 
char team3[20]; 
char team4[20]; 
char team5[20]; 
}; 


char *Arrange(struct league *table) 

{ 
struct league *Ptable[5] = {0}; 
    int i; 

    Ptable[0]-> team5; 
    Ptable[1]-> team2; 
    Ptable[2]-> team3; 
    Ptable[3]-> team1; 
    Ptable[4]-> team4; 

for (i = 0; i < 5; i++) 

    printf("%s\n", &Ptable[i]); 

return Ptable[i]; 
} 


int main() 

{ 
struct league table; 

strcpy(table.team1,"Arsenal"); 
strcpy(table.team2,"Man City"); 
strcpy(table.team3,"LiverPool"); 
strcpy(table.team4,"Totenham"); 
strcpy(table.team5,"Chelsea"); 

printf("League table:\n"); 

Arrange(&table); 


return 0; 
} 

當我編譯它,我得到這個錯誤:

warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘struct league **’ [-Wformat=] 
    printf("%s\n", &Ptable[i]); 

有什麼不對我的代碼進行太多的修改實現代碼的正確方法?因爲我想在這樣的代碼中使用結構體的指針數組。

+0

此代碼不會執行您認爲的操作。 'Ptable [i]'是一個結構聯盟的指針。每個聯盟結構有5個成員,每個成員是20個字符數組。五個Ptable [i} - > teami聲明不做任何事情。 – bruceg

+0

請注意,這是托特納姆熱刺(熱刺) - 中間有兩個t。和利物浦;沒有資本在中間。 –

回答

1

聯盟中的每個團隊都是一個字符串,而不是一個結構,所以你不需要一個結構指針數組,只需要一個指向字符串的指針數組。

char *Arrange(struct league *table) { 
    char *Ptable = malloc(5 * sizeof(char *)); 
    Ptable[0] = table->team5; 
    Ptable[1] = table->team2; 
    Ptable[2] = table->team3; 
    Ptable[3] = table->team1; 
    Ptable[4] = table->team4; 
    for (i = 0; i < 5; i++) { 
     printf("%s\n", &Ptable[i]); 
    } 
    return Ptable; 
} 

返回一個數組,你需要用malloc()動態分配,然後返回一個指針。

+0

謝謝..它的工作,我已經嘗試過,只是一個指針數組,但我寫它像這樣Ptable [0] = team5;等等..我沒有把桌子 - > ..我不明白你最後一句關於返回Ptable,但我返回Ptable [我],它也工作。 – whiteknights

+0

@whiteknights循環後,「我= 5」。沒有'Ptable [i]',通過'Ptable [4]'有效的元素是'Ptable [0]'。 – Barmar

+0

謝謝..不是Ptable [0]只是一個元素?我想返回所有的元素。 – whiteknights