-3
我正在尝试编写一个使用C的程序,该程序在给定的街道上生成每个家庭中的人数,并在嵌套for循环中使用随机数生成器。将随机数分配给2D阵列时,嵌套For-Loop不会结束。
这应该很简单,但是当我尝试将数据分配给数组中的位置时,For循环不会停止。如果我拿出这部分,for循环按照正常完成。
这一个工作,但是没有分配任何数据(我用指针测试和测试2到检查循环已经停止。):
// populating the streets with kids
// Streets then houses, we are assuming that each street is uniform in number of houses
int KidsInStreet[9][24];
for(int o = 0; o <10; o++){
printf("Testing %d\n", o);
for(int j = 0; j < 25; j++){
// assign randnumber between 0 and 5 for no of kids
int r = rand() % 5;
// KidsInStreet[o][j] = r;
printf("Testing2 %d\n", j);
}
}
,当我尝试分配数据,循环不停止:
// populating the streets with kids
// Streets then houses, we are assuming that each street is uniform in number of houses
int KidsInStreet[9][24];
for(int o = 0; o <10; o++){
printf("Testing %d\n", o);
for(int j = 0; j < 25; j++){
// assign randnumber between 0 and 5 for no of kids
int r = rand() % 5;
KidsInStreet[o][j] = r;
printf("Testing2 %d\n", j);
}
}
我有0个想法为什么发生这种情况,因为它真的不应该是一个问题。 非常感谢您的任何反馈:)
你的循环限制是关闭的情况的一个,所以你索引数组超出范围。索引的限制int KidsInStreet [9] [24];'是'KidsInStreet [8] [23] = r;'。因为这是*未定义的行为*实际行为是不相关的。 –
数组索引的范围是什么?对于九个元素的数组,有效索引范围从零到八(含)。你的外部循环上升到* 9 *,这将超出界限并导致*未定义的行为*。 –
应将数组声明为'int KidsInStreet [10] [25]'或for循环必须相应地更改为 –