繁体   English   中英

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

[英]How do I store a random string from an array of strings in c?

尝试将随机水果从数组保存到字符数组时遇到一个问题。

错误消息显示为:错误:分配给具有数组类型的表达式的结果fruit = fruit [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;
}

复制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;
}

使用strcpy (来自“ string.h”):

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

但是,如果您的结果只需要是一个常量字符串,并且您不会更改它,则只需将其声明为指针即可const char* fruit; 您就可以像以前一样进行作业。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM