Pick randomly string from array in C

2019-09-02 17:28发布

问题:

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]

回答1:

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 arrays random