C语言 c中数组中的随机元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17215242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
random element from array in c
提问by Rrjrjtlokrthjji
How can I select a random element from a character array in c ?
如何从 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.
我正在寻找类似 array[rand] 的东西,其中 rand 是 o 和数组长度(在本例中为 20)之间的随机整数,如 1、2、3、19 等。
回答by levengli
To start things off, since you have an array of strings, not of characters, you have to declare it as char* array[19];
首先,由于您有一个字符串数组,而不是字符数组,因此您必须将其声明为 char* array[19];
Then, you can declare the following (always useful) macro
然后,您可以声明以下(总是有用的)宏
#define ARR_SIZE(arr) ( sizeof((arr)) / sizeof((arr[0])) )
#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 notthe proper way to do get a random number within a range.
最后,你可以选择arr[rand() % ARR_SIZE(arr)](同时铭记在执行%上rand()是不是做得到一个范围内的随机数的正确方法。
回答by MOHAMED
int n = rand()%20;
printf("%s\n", array[n]);
回答by Alexis
You can try array[rand() % ARRAY_LEN] but you are going to get a single char and not a char*
您可以尝试 array[rand() % ARRAY_LEN] 但您将获得一个字符而不是一个 char*
and when you are doing array[0] = "Hi"; it's not correct since you are assigning to a single chara char*
当你在做 array[0] = "Hi"; 这是不正确的,因为您分配给单个charachar*
or turn your char array[20]into a char *array[20]and you can assign a string of characters
或者把你的char array[20]变成a char *array[20],你可以分配一串字符
回答by Ivaylo Strandjev
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().
您提出的是最好的解决方案 - 选择一个随机索引,然后使用该索引处的元素。如果您的问题是如何获取随机整数,请使用内置函数rand()。
回答by Nyameaama Gambrah
This can be done using rand in the c library stdlib.h
这可以在 c 库 stdlib.h 中使用 rand 来完成
You can get a random number like this:
你可以得到一个这样的随机数:
char random_elem = array[rand()%20];
char random_elem = array[rand()%20];
and you can print it out like this:
你可以像这样打印出来:
printf("%d",array[rand()%20]);
printf("%d",array[rand()%20]);

