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

时间:2017-12-22 15:54:58

标签: 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;
}

2 个答案:

答案 0 :(得分:3)

我相信您会希望使用malloccalloc来指示它。

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

完成后请确保您免费分配:

free(values);

答案 1 :(得分:0)

C允许您声明可变大小的数组。如果您对使用malloc或calloc等函数不感兴趣,可以使用变量来声明数组,就像我在这里所做的那样:

#include <stdio.h>
void main()
{
      int x;

      printf("\nEnter the value of x : ");
      scanf("%d" , &x);

      int array[x];

      for(i = 0 ; i < x ; i++)
      {
              printf("Enter the element : ");
              scanf("%d" , &array[i]);
      }

      for(i = 0 ; i < x ; i++)
      {
             printf("%d  " , array[i]);
      }
}

此程序正确运行,没有任何错误。所以你的问题在这里解决了,而不使用malloc或calloc。但是请确保在扫描之后声明您的数组,或者为您的变量赋值,这将代表数组的大小(此处:x是变量),在您的情况下我猜:player1_amount。

但是如果你想使用malloc,那么它就在这里:

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

void main()
{
    int x , i;
    int * array;

    printf("\nEnter the value of x : ");
    scanf("%d" , &x);

    array = (int *) malloc(x * sizeof(int));

    for(i = 0 ; i < x ; i++)
    {
        printf("Enter the element : ");
        scanf("%d" , &array[i]);
    }

    for(i = 0 ; i < x ; i++)
    {
        printf("%d  " , array[i]);
    }
}

两个代码都会给你相同的输出。 一点点解释......

Malloc将输入参数作为您希望分配给给定变量的内存量(在我们的例子中类似于'array'),并将输出指向该内存块的指针。 从这里我们使用整数数组,返回类型被转换为:(int *),如果它是一个字符数组,我们将其类型转换为:(char *)。