c - 将随机数分配给二维数组时,嵌套 For 循环永远不会结束。

标签 c arrays

我正在尝试使用 C 语言编写一个程序,使用嵌套 for 循环内的随机数生成器来生成给定街道上每个家庭的人数。

这应该非常简单,但是当我尝试将数据分配到数组中的位置时,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);
    }
}

我不知道为什么会发生这种情况,因为它确实不应该成为问题。 非常感谢您的任何反馈:)

最佳答案

正如 @WeatherVane 在评论中指出的,在这一行 int KidsInStreet[9][24] 中,924 是元素的数量。

将该行更改为 int KidsInStreet[10][25]; 可以解决问题:

#include "stdio.h"

int main(void) {
    // Disable stdout buffering
    setvbuf(stdout, NULL, _IONBF, 0);

    printf("Hello World\n");
    int KidsInStreet[10][25];
    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 o%d j%d\n",o, j);
        }
    }
    return 0;
}

您可以在这里尝试代码:https://repl.it/EycD/1

关于c - 将随机数分配给二维数组时,嵌套 For 循环永远不会结束。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41401291/

相关文章:

java - 如何(便宜地)计算n个可能元素的所有可能的length-r组合

c - 如何捕获系统范围内加载的库?

c - 读取整个数字而不是拆分

c - 找到许多子数组的开始和结束的算法?

C++ - 数组是指针吗?

javascript - $(selector)[0] 在 jQuery 中是什么意思?

php - 使用 PHP 连接字符串并用逗号分隔

c - 将 char 数组初始化为 NULL 奇怪的行为

java - 设置 TextView 数组的上下文

javascript - 如何使用angularjs在html中打印数组对象数组