random element from array in c

2019-08-06 05:02发布

How can I select a random element from a character array in c ?

For instance:

char *array[19];

array[0] = "Hi";


array[1] = "Hello";

etc

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.

5条回答
疯言疯语
2楼-- · 2019-08-06 05:21

To start things off, since you have an array of strings, not of characters, you have to declare it as char* array[19];

Then, you can declare the following (always useful) macro

#define ARR_SIZE(arr) ( sizeof((arr)) / sizeof((arr[0])) )

Last, you can choose arr[rand() % ARR_SIZE(arr)] (while keeping in mind that performing % on rand() is not the proper way to do get a random number within a range.

查看更多
太酷不给撩
3楼-- · 2019-08-06 05:29

This can be done using rand in the c library stdlib.h

You can get a random number like this:

char random_elem = array[rand()%20];

and you can print it out like this:

printf("%d",array[rand()%20]);

查看更多
看我几分像从前
4楼-- · 2019-08-06 05:32
int n = rand()%20;
printf("%s\n", array[n]);
查看更多
Evening l夕情丶
5楼-- · 2019-08-06 05:48

You can try array[rand() % ARRAY_LEN] but you are going to get a single char and not a char*

and when you are doing array[0] = "Hi"; it's not correct since you are assigning to a single char a char*

or turn your char array[20] into a char *array[20] and you can assign a string of characters

查看更多
Deceive 欺骗
6楼-- · 2019-08-06 05:48

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

查看更多
登录 后发表回答