gpt4 book ai didi

c - 如何扫描二维数组?

转载 作者:行者123 更新时间:2023-11-30 18:23:53 26 4
gpt4 key购买 nike

我目前正在尝试将两个整数扫描到一个数组中,它可以工作,直到我输入这两个数字并且程序崩溃。我哪里错了?

int teamWins = 0, opponentWins = 0, i = 0, gameNums = 0;
int games[1][100];

printf("Enter Number of Games for Input: ");
scanf("%d", &gameNums);

for (i = 0; i <= gameNums; i++) {
printf("Input the scores (Team vs. Opponent (ex. 10 5)): ");
scanf("%d %d", &games[1][100]);
}

printf("%d %d", games[1][100]);

return gameNums;

最佳答案

int games[1][100];

声明一个 int 二维数组,第一维 size=1,第二维 size=100。第一个维度中的唯一有效索引是 0,第二个维度中的有效索引是 0-99

现在检查以下语句:

scanf("%d %d", &games[1][100]);

这里有两个问题,都是未定义的行为。

1) 该语句尝试从标准输入读取两个整数,但只提供一个目标

根据standard :(感谢@DavidBowling 的引用)

The fscanf function reads input from the stream pointed to by stream, under control of the string pointed to by format that specifies the admissible input sequences and how they are to be converted for assignment, using subsequent arguments as pointers to the objects to receive the converted input. If there are insufficient arguments for the format, the behavior is undefined.

2) games[1][100] 处的值已超出数组范围。

关于c - 如何扫描二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48554189/

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