我正在编写一个代码来帮助圣诞老人跟踪街道所需的礼物数量,我正在尝试通过使用2D数组并嵌套for循环,显然这是正确的方式这样做,但程序往往在要求第二宫的孩子数量后崩溃。代码如下所示:
void distribute_presents()
{
int houses, kids=0;
int KidsInStreet[houses][kids];
int i, j;
printf("Enter the number of houses in the street?\n");
scanf("%d", &houses);
printf("Enter the number of kids in the street?\n");
scanf("%d", &kids);
for (i=0;i<=houses;i++)
{
for (j=0;j<=kids;j++)
{
printf("Enter the number of kids in house %d:\n", i+1, j+1);
scanf("%d", KidsInStreet[i][j]);
}
}
printf("The presents and their respective prices are:\n");
for(i=0;i<=houses;i++)
{
for(j=0;j<=kids;j++)
{
printf("%d", KidsInStreet[i][j]);
}
}
}
答案 0 :(得分:3)
我认为你应该首先查询房屋和孩子的数量,然后填充2D数组:
void distribute_presents()
{
int houses, kids = 0;
int i, j;
printf("Enter the number of houses in the street?\n");
scanf("%d", &houses);
printf("Enter the number of kids in the street?\n");
scanf("%d", &kids);
int KidsInStreet[houses][kids];
for (i=0; i < houses; i++)
{
for (j=0; j < kids; j++)
{
printf("Enter the number of kids in house %d:\n", i+1);
scanf("%d", &KidsInStreet[i][j]);
}
}
printf("The presents and their respective prices are:\n");
for (i=0; i < houses; i++)
{
for (j=0; j < kids; j++)
{
printf("%d", &KidsInStreet[i][j]);
}
}
}