Reputation: 73
I`m trying to generate random sentences but sometimes i got an error or it prints random characters. Below is what i done. (the sentences should have the folowing format: article , noun , verb, preposition, article and noun).
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
#include <string.h>
int main() {
srand(time(NULL));
int r1, r2, r3, r4, r5, r6;
char *article[] = {"the" , "a" , "one" , "some", "any"};
char *noun[] = {"boy" , "girl" , "dog" , "town", "car"};
char *verb[] = {"drove" , "jumped" , "ran" , "walked", "skipped"};
char *preposition[] = {"to" , "from" , "over" , "under", "on"};
r1 = rand() % 6; r2 = rand() % 6; r3 = rand() % 6; r4 = rand() % 6; r5 = rand() % 6; r6 = rand() % 6;
printf("%s %s %s %s %s %s\n", article[r1], noun[r2], verb[r3], preposition[r4], article[r5], noun[r6]);
return 0;
}
Upvotes: 1
Views: 2387
Reputation: 140168
All your lists have less than 6 elements, so from time to time, the random routine returns a value outside the list bounds: read a garbage pointer => undefined behaviour. So now the "random" bug is explained.
Now what happens when you (or another developper) add or remove elements to one list? you have to adjust sizes again.
I'd create a small macro to avoid doing that:
#define RANDSTRING(s) s[rand() % (sizeof(s)/sizeof(*(s)))]
now:
const char *r = RANDSTRING(noun);
picks a value in the noun
list, guaranteed to be in bounds.
it works on lists of strings and computes the size correctly. It won't work on pointers on pointers like char **
, though.
It also doesn't work on empty lists (% 0
is illegal, and it makes no sense anyway)
Upvotes: 2
Reputation: 30926
r1 = rand() % 6;
have values 0,1,2,3,4,5
But the first array has 5
elements. So you were accessing array index out of bound and were having undefined behavior.
Instead
r1 = rand() % arraysize;
This works.(Same you have to do for other arrays also).
So for example in the first case arraysize = 5
so r1= rand()%5
and for r2=rand()%5
etc. (Here you have array size = 5 for all the arrays).
Getting the array size will be like this in this case
r2 = rand()%( sizeof noun/ sizeof noun[0] );
Upvotes: 4