当我打印一个列表的所有变量时,它给了我一个在 c 中不一致的意外值。你能告诉我哪里出了问题吗?

When I print all the variables of a list it gives me an unexpected value that is inconsistent in c. Can you tell me what went wrong?

这是代码

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

struct rule {
    int id;
    int allow[3];
};

char key_id[10] = { '\', '/', '`', '#', '_', '*', '@', '%', '>', '<' };

struct rule def_rule(int id, int *arr, int arr_size) {
    struct rule temp;
    temp.id = id;
    for (int i; i < arr_size; i++) {
        temp.allow[i] = arr[i];
    }
    return temp;
}

void collapse(int *map, int map_w, int map_h) {
    srand(time(0));
    //finding adj indexes
    int nth;
    int wst;
    int sth;
    int est;
    int map_a = map_h * map_w;
    int dir[4] = { nth, wst, sth, est };
    for (int i = 0; i < map_w * map_h; i++) {
        if ((i - 4) >= 0) {
            nth = map[i - 4];
        }

        if ((i + 1) < map_a) {
            wst = map[i + 1];
        }

        if (i + 4 <= 15) {
            sth = map[i + 4];
        }

        if (i - 1 >= 0) {
            est = map[i - 1];
        }
    }
}


void main(void) {
    //define some rules
    struct rule rules[0];
    int arr[3] = { 0, 1, 2 };
    rules[0] = def_rule(0, arr, 3);

    //collapse
    int map_w = 4;
    int map_h = 4;
    int map[map_w * map_h];
    for(int i = 0; i < 15; i++) {
        map[i] = 0;
    }
    collapse(map, map_w, map_h);
    for (int i = 0; i < map_w; i++) {
        for (int j = 0; j < map_h; j++) {
            printf(" %d ", map[(i * 4) + j]);
        }
        printf("\n");
    }
}

当我编译它时,它没有给我任何错误或警告,我认为当我访问 map[i] 时我没有超出范围。 但是它在我的终端中给了我这个输出:

 0  0  0  0 
 0  0  0  0 
 0  0  0  0 
 0  0  0  21896

当我再次 运行 时 21896 更改为不同的数字。

我正在尝试根据某些规则将数组中的零转换为其他数字。 我制作了检查邻接的代码,这样它就不会改变变量映射。 唯一一次更改变量映射是当我迭代它以将所有内容设置为 0 时。 我已经测试了所有代码,它似乎可以工作,但是当我添加结构时它开始执行此操作。

编辑:

问题是我正在访问地图的最后一个索引以外的所有内容,所以我想打印一个未定义的变量。

map 的初始化循环不正确:您从未初始化最后一个元素。你应该使用:

    int map[map_w * map_h];
    for (int i = 0; i < map_w * map_h; i++) {
        map[i] = 0;
    }