我正在尝试创建一个程序,该程序随机决定您拥有多少张卡片,然后随机为每张卡片分配一个值。 我设法随机化了卡片的数量,并且我知道如何使用数组和 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;
}
最佳答案
我相信你会想要使用 malloc或 calloc为此用一个指针。
int *values = (int *)calloc(player1_amount, sizeof(int));
只需确保在完成后释放您的分配:
free(values);
关于c - 如何创建一个未定义长度的数组? (在 C 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47944182/