从C中的数组随机挑选字符串 [英] Pick randomly string from array in C

查看:173
本文介绍了从C中的数组随机挑选字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 无效选秀权(){
    字符*字[2];
    字[0] =嗒嗒;
    词语[1] =嗯;    烧焦随机的;
    函数srand(时间(NULL));
    随机=字[兰特()%2];
    的printf(随机);
    返回;
}

这是我的code,我想随机挑选从文字排列一个词,但是当我运行它的编译器说:【警告】赋值时将指针整数,未作施放[默认启用]


解决方案

您已经声明随机字符,它是一个单字节的整数值。你分配给它从字的元素数组,每一元素的类型为的char * 。因此,你得到关于设法一个的char * 分配到一个整数值错误。

您的意思声明随机的char *

其他的事情,我会指出你的code:

 无效选秀权(){
    字符*字[2]; // 1
    字[0] =嗒嗒;
    词语[1] =嗯;    烧焦随机的; // 2
    函数srand(时间(NULL));
    随机=字[兰特()%2]; // 3
    的printf(随机); // 4
    返回;
}


  1. 这应该被声明为数组为const char *

    <因为你指定字符串(这是不可改变的)它。 / LI>
  2. 随机也应被声明为为const char *


  3. 使用在一个特定的范围内获得的随机数历来不是很好。另请参见 Q13.16我如何获得随机整数在一定范围内? 从comp.lang.c常见问题。


  4. 的printf(随机)是危险的。如果你要打印字符串恰好包括字符,那么的printf 将行为不端(这可能可能是一个安全漏洞)。你应该总是preFER 的printf(%S,随机)。因为你可能想尾随换行,它应该是的printf(%S \\ n,随机)或只是看跌期权(随机)


void pick() {
    char* words[2];
    words[0] = "blah";
    words[1] = "hmm";

    char random;
    srand(time(NULL));
    random = words[rand() % 2];
    printf(random);
    return;
}

This is my code and I want to pick randomly a word from words array but when I run it the compiler says: [Warning] assignment makes integer from pointer without a cast [enabled by default]

解决方案

You've declared random as a char, which is a single byte integral value. You're assigning to it an element from the words array, and each of those elements is of type char*. Hence, you are getting an error about trying to assign a char* to an integer value.

You meant to declare randomas a char*.

Other things I'll point out about your code:

void pick() {
    char* words[2]; // 1
    words[0] = "blah";
    words[1] = "hmm";

    char random; // 2
    srand(time(NULL));
    random = words[rand() % 2]; // 3
    printf(random); // 4
    return;
}

  1. This should be declared as an array of const char* since you're assigning string literals (which are immutable) to it.

  2. random also should be declared as const char*.

  3. Using % to get random numbers in a specific range traditionally is not very good. Also see Q13.16 How can I get random integers in a certain range? from the comp.lang.c FAQ.

  4. printf(random) is dangerous. If the string you're printing happens to include % characters, then printf will misbehave (and this potentially could be a security vulnerability). You always should prefer printf("%s", random). And since you probably want a trailing newline, it ought to be printf("%s\n", random) or just puts(random).

这篇关于从C中的数组随机挑选字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆