我正在尝试将我的二维数组中的所有值设置为 0,然后打印所有分数以确保它们是正确的。
struct Game {
int GameScoresHome[10][10];
};
int main() {
struct Game game;
memset(game.GameScoresHome, 0, sizeof game.GameScoresHome);
for (int x=0;x<100;x++) {
int y = floor(x/10);
printf("%d ",game.GameScoresHome[x][y]);
}
return 0;
}
当前输出为:
0 0 0 0 0 0 0 0 0 0 0 0 822083893 32767 32767 32767 32767 32767 32767 1651067951 1634028652 1345283180 1702057263 1701080931 2054842477 1866870631 1885417061 1647262318 1146113364 896624241 1280918623 1919052108 1819042146 1818850626 1634956149 1852133983 1264923239 792545364 1666723698 1836345960 1163089152 1949263220 1919250021 1868774725 1213481296 796026224 1785230711 1650803759 792546380 1213481296 1868781615 1752003690 6780258 1497628720 778396783 1920232291 792545364 1666723698 1836345960 1735746149 796026224 1785230711 1650803759 0 0 3 0 7 0 -2147482624 0 0 0 0 0 0 0 0 0 0 233472 1869045599 48 1868783455 5312 1633967967 3480 1818320735 304 1919115103 0 1852796269 0 115 0 72 0 1227 0 0
前 11 个零是它们应该的,然后一切都出错了。怎么回事?
最佳答案
您正在访问数组外的内存。
您的 x
变量从 0 迭代到 99。
for (int x=0;x<100;x++)
但是你的数组只有 10 行。
int GameScoresHome[10][10];
一个解决方法是使用简单的嵌套循环。
for (int x=0;x<10;x++) {
for (int y=0;y<10;y++) {
printf("%d ",game.GameScoresHome[x][y]);
}
}
嵌套循环还可以轻松地在每一行之后包含一个换行符。
for (int x=0;x<10;x++) {
for (int y=0;y<10;y++) {
printf("%d ",game.GameScoresHome[x][y]);
}
printf("\n");
}
关于c - 在 C 中将二维整数数组值全部设置为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32101239/