This is an improved version of my random monster program. This shows how to get the size of a const char array and then select a random entry from the array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | #include <stdio.h> #include <stdlib.h> #include <time.h> char *cuserid(char *s); const char* x[] = { "Baron of Hell", "Demon", "Hellknight", "Cyberdemon", "Mancubus", "Revenant", "Heretic Imp", "Zombieman", "Sergeant", "Beholder", "Moloch", "Satyr", "Afrit", "Ettin", "Maulator", }; int cool(void) { int k; size_t i = sizeof(x) / sizeof(x[0]); k = 0; srand((unsigned)time(NULL)); k = rand() % i; return k; } int main() { char myname[128]; char *player; cuserid(myname); printf("%s was slaughtered by a %s.\n",myname , x[cool()]); return 0; } |
This section of code gets the proper size of the x[] array.
size_t i = sizeof(x) / sizeof(x[0]); <pre> This function gets a random number that will equate to an entry in the array. <pre lang="c" line="1"> int cool(void) { int k; size_t i = sizeof(x) / sizeof(x[0]); k = 0; srand((unsigned)time(NULL)); k = rand() % i; return k; } |
Then in the main() we can call printf(3) to print a random entry.
printf("%s was slaughtered by a %s.\n",myname , x[cool()]); |
This is quite simple, but I need to find a random number function that generates numbers faster, still, it is adequate for my needs in this example.