从C中的数组随机挑选字符串 [英] Pick randomly string from array in C
问题描述
无效选秀权(){
字符*字[2];
字[0] =嗒嗒;
词语[1] =嗯; 烧焦随机的;
函数srand(时间(NULL));
随机=字[兰特()%2];
的printf(随机);
返回;
}
这是我的code,我想随机挑选从文字排列一个词,但是当我运行它的编译器说:【警告】赋值时将指针整数,未作施放[默认启用]
您已经声明随机
为字符
,它是一个单字节的整数值。你分配给它从字的元素
数组,每一元素的类型为的char *
。因此,你得到关于设法一个的char *
分配到一个整数值错误。
您的意思声明随机
为的char *
。
其他的事情,我会指出你的code:
无效选秀权(){
字符*字[2]; // 1
字[0] =嗒嗒;
词语[1] =嗯; 烧焦随机的; // 2
函数srand(时间(NULL));
随机=字[兰特()%2]; // 3
的printf(随机); // 4
返回;
}
-
这应该被声明为数组
<因为你指定字符串(这是不可改变的)它。 / LI>为const char *
-
随机
也应被声明为为const char *
。 -
使用
%
在一个特定的范围内获得的随机数历来不是很好。另请参见 Q13.16我如何获得随机整数在一定范围内? 从comp.lang.c常见问题。 -
的printf(随机)
是危险的。如果你要打印字符串恰好包括%
字符,那么的printf
将行为不端(这可能可能是一个安全漏洞)。你应该总是preFER的printf(%S,随机)
。因为你可能想尾随换行,它应该是的printf(%S \\ n,随机)
或只是看跌期权(随机)
。
void pick() {
char* words[2];
words[0] = "blah";
words[1] = "hmm";
char random;
srand(time(NULL));
random = words[rand() % 2];
printf(random);
return;
}
This is my code and I want to pick randomly a word from words array but when I run it the compiler says: [Warning] assignment makes integer from pointer without a cast [enabled by default]
You've declared random
as a char
, which is a single byte integral value. You're assigning to it an element from the words
array, and each of those elements is of type char*
. Hence, you are getting an error about trying to assign a char*
to an integer value.
You meant to declare random
as a char*
.
Other things I'll point out about your code:
void pick() {
char* words[2]; // 1
words[0] = "blah";
words[1] = "hmm";
char random; // 2
srand(time(NULL));
random = words[rand() % 2]; // 3
printf(random); // 4
return;
}
This should be declared as an array of
const char*
since you're assigning string literals (which are immutable) to it.random
also should be declared asconst char*
.Using
%
to get random numbers in a specific range traditionally is not very good. Also see Q13.16 How can I get random integers in a certain range? from the comp.lang.c FAQ.printf(random)
is dangerous. If the string you're printing happens to include%
characters, thenprintf
will misbehave (and this potentially could be a security vulnerability). You always should preferprintf("%s", random)
. And since you probably want a trailing newline, it ought to beprintf("%s\n", random)
or justputs(random)
.
这篇关于从C中的数组随机挑选字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!