c - 用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;
}
解决方案
您可以使用动态内存分配,这将允许您声明一个未知大小的数组以供以后使用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;
}
推荐阅读
- c# - 将数据从一个数据库批量复制或更新到另一个数据库
- php - 由于不活动,该页面已过期。拉拉维尔
- python - OpenCV RTSP 捕获未打开
- django - django 从上下文数据自动填充表单字段
- python - 创建叶节点为
代替 在 Python 3 中使用 xml.etree.ElementTree - graphql - 使用阿波罗客户端忽略突变查询的结果?
- javascript - 迭代Nodejs中的元素
- c# - Compact Framework 和 Full Framework 的 DllImport 区别
- java - spring boot(webflux)rest控制器获取远程IP地址
- java - wsimport 生成的 java 类 - 401 错误