gpt4 book ai didi

c - 用 C 编程,如何声明以后使用的未知大小的数组?

转载 作者:太空宇宙 更新时间:2023-11-04 06:13:57 24 4
gpt4 key购买 nike

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

scanf 会输入合法牌的张数。然后我想创建一个该大小的数组。

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

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

我希望获得有关如何更好地编写此程序的建议。(我仍然需要使用 scanf 来获取输入,但也许有更好的方法 o

是将所有与数组相关的代码都放在 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;
}

最佳答案

您可以使用动态内存分配,这将允许您声明一个未知大小的数组,以便稍后在运行时使用。

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

#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;
}

关于c - 用 C 编程,如何声明以后使用的未知大小的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50167915/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com