1

How can I pass a string from an array into a function? I want to pass a string such as "Battleship" into the function print() and have it 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);
}
4

3 回答 3

2

Let print take a char const * instead of a single char. Then, drop the * from the call:

print(ships_name[index]);
于 2012-10-28T23:13:59.770 回答
0

您需要使您的打印函数采用指向字符的指针,而不是字符。这是因为在 C 中,字符串只是一个内存位置,其中包含一些以空字节结尾的字符。

您应该将 print 的签名更改为

void print(char *ship_names)
于 2012-10-28T23:14:21.187 回答
0

我认为与其取消引用指向 shipname[index] 字符串的指针,不如传递字符串指针本身,并使用print(ships_name[index])该指针传递指向字符串的指针。然后,您的方法将必须采用 char *。

于 2012-10-28T23:16:25.833 回答