在C中将二维整数数组值全部设置为0
我正在尝试将2D数组中的所有值设置为0,然后打印所有分数,以确保它们是正确的在C中将二维整数数组值全部设置为0,c,arrays,integer,C,Arrays,Integer,我正在尝试将2D数组中的所有值设置为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);
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;
}
前11个零是应该的,然后一切都出错了。发生了什么事?在您的代码中
for (int x=0;x<100;x++) {
int y = floor(x/10);
printf("%d ",game.GameScoresHome[x][y]);
}
或者,使用嵌套循环分别维护两个索引。您正在访问数组外部的内存 您的
x
变量从0迭代到99
for (int x=0;x<100;x++)
一种修复方法是使用简单的嵌套循环
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编写更简单的循环
for ( int x = 0; x < 100; x++) {
printf("%d ",game.GameScoresHome[x / 10][x % 10]);
}
无效。y的计算不正确。怎么办
struct Game game = {.GameScoresHome = {0}};
for (int x=0;x<10;x++) {
for (int y=0;y<10;y++) {
printf("%d ",game.GameScoresHome[x][y]);
}
printf("\n");
}
struct-Game-Game={.GameScoresHome={0};
对于(intx=0;xUseprintf(“%d”,game.GameScoresHome[x%10][y]);
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");
}
for ( int x = 0; x < 100; x++) {
printf("%d ",game.GameScoresHome[x / 10][x % 10]);
}
for ( int x = 0; x < 100; x++) {
printf("%d ",game.GameScoresHome[x / 10][x % 10]);
if ( x % 10 == 9 ) printf( "\n" );
}
printf("%d ",game.GameScoresHome[x][y]);
^^^
struct Game game = {.GameScoresHome = {0}};
for (int x=0;x<10;x++) {
for (int y=0;y<10;y++) {
printf("%d ",game.GameScoresHome[x][y]);
}
printf("\n");
}