如何在c中存储字符串数组中的随机字符串?

时间:2017-01-11 01:56:07

标签: c arrays string char

当我尝试将数组中的随机水果保存到一组字符时,我遇到了一个问题。

错误消息显示:error:赋值给具有数组类型的表达式   fruit = fruits [rand()%20];

具体来说,这两行似乎是个问题:

char fruit[20];
fruit = fruits[rand() % 20];

我尝试将它组合成一行,例如:

char fruit[] = fruits[rand() % 20];

但这也行不通。 我试图从别人的帖子中弄清楚这一点,但我似乎无法弄清楚原因。如果有人有修复或正确的方法,我会非常感激。感谢。

完整代码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main () {
time_t t;
const char *fruits[20] = {"apple", "pear", "orange", "banana", "watermelon", "cantaloupe", "grape", "kiwi", "blackberry", "blueberry", "raspberry", "cherry", "strawberry", "lemon", "lime", "plum", "pineapple", "peach", "mango", "olive"};   

srand((unsigned) time(&t));

char fruit[20];
fruit = fruits[rand() % 20];

printf("\nrandom fruit is %s\n", fruit);
return 1;
}

2 个答案:

答案 0 :(得分:1)

当您复制C 字符串时,您不会使用赋值,因为这会尝试将指针复制到字符串。试图将其复制到数组变量是造成问题的原因。

相反,请使用string.h设施:

strcpy (fruit, fruits[someRandomIndex]);

并确保您永远不会将golden delicious apple添加到水果列表中,因为它会轻易覆盖19个字符的限制: - )

但实际上,您实际上并不需要 来复制字符串,因为您可以将原始指针传递给printf。您还可以清理代码以便于维护:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main (void) {
    // Const pointer to const data generally allows more
    // scope for optimisation. Also auto size array.

    static const char const *fruits[] = {
        "apple", "pear", "orange", "banana", "watermelon",
        "cantaloupe", "grape", "kiwi", "blackberry",
        "blueberry", "raspberry", "cherry", "strawberry",
        "lemon", "lime", "plum", "pineapple", "peach",
        "mango", "olive"};   
    static const int fruitCount = sizeof(fruits) / sizeof(*fruits);

    // Seed generator, no need to store, just use it.

    srand ((unsigned) time(0));

    // Get random pointer based on size, and print it.

    printf ("Random fruit is %s\n", fruits[rand() % fruitCount]);

    // Return usual success code.

    return 0;
}

答案 1 :(得分:1)

使用strcpy(来自&#34; string.h&#34;):

strcpy(fruit, fruits[rand() % 20]);

但是,如果你的结果只需要是一个常量字符串而你不会改变它,只需将它声明为一个指针const char* fruit;就可以像你一样进行赋值。