首页 > 解决方案 > 用C编程,如何声明未知大小的数组以供以后使用?

问题描述

我正在为一个简单的纸牌游戏创建一个 AI 播放器。

scanf 将输入合法卡片的数量。然后我想创建一个该大小的数组。

但是,如果用户输入为 0,我添加了一个 if 语句以防止错误。(因为您无法创建指向大小为 0 的数组。)

我的问题是......因为我在 if 语句中创建了它,所以我无法在 if 语句之外访问它。当我尝试在我的 Mac 上使用 Xcode 进行编译时,警告“使用未声明的标识符 'legal_cards'”表明了这一点。

我很想得到关于如何更好地编写这个程序的建议。(我仍然需要使用 scanf 来获取输入,但也许有更好的方法

是在 if 语句中拥有与数组相关的所有代码的唯一方法吗?或者我可以稍后使用它(使用另一个 if 语句检查以确保(n_legal_cards > 0)

#include <stdio.h>

int main (void) {
    int n_legal_cards;

    printf("How many legal cards are there?\n");
    scanf("%d", &n_legal_cards);

    if (n_legal_cards > 0) {
        int legal_cards[n_legal_cards];
    }

    /*
    ...
    [scanning other variables in here]
    [a little bit of other code here]
    ...
    */


    if (n_legal_cards > 0) {
        int rounds_suit = legal_cards[0];
    }

    return 0;
}

标签: c

解决方案


您可以使用动态内存分配,这将允许您声明一个未知大小的数组以供以后使用at runtime

这是您可以执行的操作的示例:

#include <stdio.h>

int main (void) {
int n_legal_cards;
int* legal_cards;

printf("How many legal cards are there?\n");
scanf("%d", &n_legal_cards);

if (n_legal_cards > 0) {

    legal_cards = malloc(n_legal_cards * sizeof(int));

}


 /*
 ...
[scanning other variables in here]
[a little bit of other code here]
...
 */


if (n_legal_cards > 0) {
int rounds_suit = legal_cards[0];
}


    return 0;
}

推荐阅读