我如何可以选择在C字符数组随机元素?
How can I select a random element from a character array in c ?
例如:
char *array[19]; array[0] = "Hi"; array[1] = "Hello";等
我要寻找像数组[兰德],其中RAND是O和数组的长度之间的随机整数(在本例中20),如1,2,3,19等。
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.
推荐答案要开始做事了,因为你有一个字符串数组的不是字符,您必须将其申报为的char *数组[ 19];
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])))
最后,你可以选择改编[兰特()%ARR_SIZE(ARR)] (同时牢记执行%在兰特()为不可以的正确方法做的范围内得到一个随机数。
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.
更多推荐
从C中的数组随机元素
发布评论