2012-10-28 42 views
1

如何將字符串從數組傳遞到函數? 我想一個字符串,如"Battleship"傳遞到功能print()並將其打印"Where would you like to place the Battleship?"我可以將字符串傳遞給函數嗎?

#include <stdio.h> 

void print(char ship_names); 

int main (void) 
{ 
    int index = 0; 
    char ships_name[5][21]= { "Aircraft Carrier (5)", "Battleship (4)", "Submarine (3)", 
           "Cruiser (3)", "Destroyer (2)"}; 

    for(index = 0; index < 5; index++) 
     print(*ships_name[index]); 

return 0; 
} 

void print(char ship_names) 
{ 
    printf("Where would you like to place the %s?\n", ship_names); 
} 

回答

2

print採取char const *而不是單個char。然後,從掉話的*

print(ships_name[index]); 
0

你需要讓你的打印功能需要一個指向字符,而不是字符。這是因爲在C中,一個字符串只是一個內存位置,其中包含一些以空字節結尾的字符。

您應該打印的簽名更改爲

void print(char *ship_names) 
0

我想,而不是取消引用指針shipsname [指數]的字符串,你應該把這個字符串指針本身print(ships_name[index])它傳遞一個字符串指針。你的方法將不得不採取一個char *。

相關問題