How can I select a random element from a character array in c ?
char *array; array = "Hi"; array = "Hello";
I am looking for something like array[rand], where rand is the random integer number between o and the array's length(in this case 20) like 1, 2, 3 , 19 etc.Answer1:
To start things off, since you have an array of strings, not of characters, you have to declare it as
Then, you can declare the following (always useful) macro
#define ARR_SIZE(arr) ( sizeof((arr)) / sizeof((arr)) )
Last, you can choose
arr[rand() % ARR_SIZE(arr)] (while keeping in mind that performing
rand() is <strong>not</strong> the proper way to do get a random number within a range.
int n = rand()%20;
You can try array[rand() % ARRAY_LEN] but you are going to get a single char and not a
and when you are doing array = "Hi"; it's not correct since you are assigning to a single
or turn your
char array into a
char *array and you can assign a string of characters
What you propose is the best solution there is - choose a random index and then use the element at this index. If your question is how to get a random integer, use the built-in function