想要打乱 char *array 并使元素随机排列
我读到Shuffle array in C但对于 int
我试试
const char *words = { "one", "two", "three", "four", "five", "six" };
for (int i=0; i<6; i++)
{
int r = (rand() % (6 - i)) + i;
int temp = words[i];
words[i] = words[r];
words[r] = temp;
}
迭代数组单词时出错
请解释一下
最佳答案
正如评论中所说,你有几个问题
const char *words = { "one", "two", "three", "four", "five", "six" };
无效,因为初始化(以及其余代码)指示words是一个数组,因此将其替换为
const char *words[] = { "one", "two", "three", "four", "five", "six" };
int temp = words[i]; words[i] = words[r]; words[r] = temp;
words 是一个 const char *
数组,因此 temp 不能是 int,请使用
const char * temp = words[i];
除此之外
- 使用文字 6 是危险的,请使用 sizeof 来考虑 单词 将 6 替换为
sizeof(字数)/sizeof(*字数)
- 索引的正确类型是
size_t
, - 为了不总是有相同的执行,请使用 srand 例如当前时间
例如:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
const char *words[] = { "one", "two", "three", "four", "five", "six" };
const size_t nelts = sizeof(words)/sizeof(*words);
srand(time(NULL));
for (size_t i=0; i < nelts; ++i)
{
size_t r = (rand() % (nelts - i)) + i;
const char * temp = words[i];
words[i] = words[r];
words[r] = temp;
}
/* show */
for (size_t i=0; i < nelts; ++i)
puts(words[i]);
return 0;
}
编译和执行:
pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out
four
one
two
five
three
six
pi@raspberrypi:/tmp $ ./a.out
one
three
two
four
five
six
pi@raspberrypi:/tmp $ ./a.out
six
five
two
four
three
one
pi@raspberrypi:/tmp $ ./a.out
three
one
five
four
six
two
关于C 洗牌二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56920179/