C 洗牌二维数组

标签 c arrays multidimensional-array random

想要打乱 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/

相关文章:

javascript - 无法通过函数参数传递对象属性名称

javascript - 在AngularJS中按两级分层组织对象

将多维数组转换为一维数组的算法

php - 更新多维数组sql php

无法从 Fortran 90 中返回的 C 浮点指针获取数据

arrays - 从 Swift 字典中删除 AnyObject

javascript - 如何根据对象的id获取数据

c - 以最有效的方式读取 CGI POST 数据

c - Minix - 将数据从系统调用地址复制回调用进程

c - 需要一些帮助以完成作业