c - 如何创建一个未定义长度的数组? (在 C 中)

标签 c arrays

我正在尝试创建一个程序,该程序随机决定您拥有多少张卡片,然后随机为每张卡片分配一个值。 我设法随机化了卡片的数量,并且我知道如何使用数组和 for 循环来随机化它们的值,但问题是此方法仅在我手动为数组中的元素数量选择值时才有效,但我希望元素的数量是卡片的随机数量。 我该怎么做? 到目前为止,这是我的代码来说明我的意思。是的,我知道代码可能会做得更好,但这是我的第一个 C 作业,我是一个完全的初学者。 谢谢:)

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

int main(void)
{
    system("cls"); /* Clears output to start */

    srand(time(NULL)); /* Sets seed for random number generator */

    int player1_amount = rand() %9 + 2; /*Generates random number for player 1's amount of cards */
    int player2_amount = rand() %9 + 2; /*Generates random number for player 2's amount of cards */

    int a = 1; /* For loop purposes */
    while(a <= 1) /* While loop to print out each player's amount of cards once */
    {
        printf("Player 1 you have %d cards! \n", player1_amount);  
        Sleep(500);
        printf("Player 2 you have %d cards! \n", player2_amount);  
        a++; 
    }    

    Sleep(1000); /* Delays for 1 second before printing card values */

    int values[3]; /* Creates an array with 3 elements, but I want the number of elements to be player1_amount from above */
    int b; /* Random variable for the loop */
    int size = sizeof(values) / sizeof(values[0]); /* Gets length of array */

    for (b = 0; b < size; b++) /* For loop randomises 3 values and then stops */
    {
        values[b] = rand() % 10 +1;
    }

    printf("Player 1 your cards are"); /* For loop to print out the values one after the other */
    for(b = 0; b < size; b++)
    {
        printf(" %d, ", values[b]);
    }

    getch();
    return 0;
}

最佳答案

我相信你会想要使用 malloccalloc为此用一个指针。

int *values = (int *)calloc(player1_amount, sizeof(int));

只需确保在完成后释放您的分配:

free(values);

关于c - 如何创建一个未定义长度的数组? (在 C 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47944182/

相关文章:

c++ - 将 float 转换为 int,有和没有转换

c - 什么时候在 c 中使用 typedef?

在 Eclipse 中到达 "printf"时无法继续进入 Debug模式

java - 如何从字符串数组或数组列表创建一个字符串?

javascript - 获取 JavaScript 数组元素的最大长度

c - 使用 gdb 和 tty 命令在单独的终端中调试时无法将数据输入到 C 程序

c - 构建文件时 Eclipse CDT 错误

Javascript - 循环内多个 http 请求的映射数据(并按属性分组)

arrays - 为什么这个函数显示的是一个数组的数组而不是一个数组?

android - 我可以在其中存储点以加快绘制速度的可绘制对象?