创建一个随机数数组并在 C 中返回该数组

标签 c

我想创建一个名为 get_lotto_draw 的函数,它将创建一个包含 6 个随机数的数组并将它们返回到 main。

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    get_lotto_draw()
    {
        int lottery[50];
        int u,i,j,temp;
        int lotto[6];

        srand(time(NULL));
            for (i =0; i<49; i++)
                lottery[i] = i+1;


            for (i =0; i<49; i++)
            {
                j = (rand()%49)+1;

                temp = lottery[i];
                lottery[i] = lottery[j];
                lottery[j] = temp;
            }

                for (i =0; i<6; i++)    
                {
                    lotto[i] = lottery[i];
                }

            return lotto;           
    }

最佳答案

#include <stdio.h>
#include <stdlib.h>
#include <time.h>



  void get_lotto_draw(int lotto[])
    {
        int lottery[50];
        int u,i,j,temp;

        for (i =0; i<49; i++)
            lottery[i] = i+1;


        for (i =0; i<49; i++)
        {
            j = (rand()%49)+1;

            temp = lottery[i];
            lottery[i] = lottery[j];
            lottery[j] = temp;
        }

            for (i =0; i<6; i++)    
            {
                lotto[i] = lottery[i];
            }

        return ;           
}

int _tmain(int argc, _TCHAR* argv[])
{
        int lotto[6];

    srand(time(NULL));

    get_lotto_draw(lotto);
    for (int i = 0; i < 6; i ++)
        printf ("%d ", lotto[i]);

    printf ("\n");

    return 0;
}

函数get_lotto_draw将采用数组“lotto”作为参数 - 未调整大小的数组。 如果您在函数内将lotto声明为自动变量,那么当函数结束时 - 自动变量lotto将被删除 - 检查此link了解详情。 因此,您在 main 中声明 lotto 并将其传递给函数。

其他选项包括

  • 在 get_lotto_draw 中使用 malloc(为“lotto”分配内存)并在 main 中使用 free(除非你非常小心 - 这会导致内存泄漏 - 我不推荐这样做)
  • 在main中使用malloc并将分配的内存传递给函数并稍后在main中释放它
  • 创建一个静态并使用它。

我的建议是在这种情况下使用堆栈(上面使用的自动变量),否则使用 malloc/free。

我修复了其他人指出的一些错误

关于创建一个随机数数组并在 C 中返回该数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29331552/

相关文章:

c++ - 是不是所有的c库都可以在c++中使用?

c++ - `undefined reference` 尝试连接 C 以调用 C++

c - 在 Linux 中关闭应用程序的 Shell 脚本

c - fgets 从提示符中读取换行符

c - 从文件加载数组

我可以使用 fscanf 将 stdout 作为 FILE 流吗?

c - 在Ada中实现变量数据耦合到函数中(类似于C中函数中的静态变量)

objective-c - 10.4 中的内部和外部 IP 地址

C - 获取数字而不是字符串

c - Visual Studio - 在 64 位项目中编译 32 位代码