'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?
Here is the code
#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");
}
}
When I compile it it doesn't give me any errors or warnings and I think when I access map[i] I am not out of range.
However it gives me this output in my terminal:
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 21896
When I run it again 21896 changes to a different number.
I am trying to turn zeros in an array into other numbers depending on some rules. I made the code for checking adjacency such that it doesn't change the variable map. The only time variable map is changed is when I iterate over it to set everything to 0. I have tested all the code and it seemed to work however when I added structs it started to do this.
Edit:
The problem was that I was accessing all but the last index of map so I was trying to print an undefined variable I think.
Solution 1:[1]
The initialization loop for map is incorrect: you never initialize the last element. You should use:
int map[map_w * map_h];
for (int i = 0; i < map_w * map_h; i++) {
map[i] = 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | chqrlie |
