1
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 Answer 1

5

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).

Sign up to request clarification or add additional context in comments.

2 Comments

i already tried that but i dont know why i get this error with char* random: c:\program files (x86)\dev-cpp\mingw32\mingw32\bin\ld.exe cannot open output file C:\Users.... Permission denied
That's a different problem, and it's a linking problem and not a compilation problem. What's the full error message? Which file is it trying to open? It sounds like ld is trying to write to a file that you already have open. Are you trying to build while it's already running?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.