I'd like to have an array of instances of TestStruct with a single member of type int. I'd like the output to be
1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6
but it is 0, 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
I'm a little stumped, because I don't really get how this isn't working:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int num;
} TestStruct;
int main(void) {
int i, j;
TestStruct *test = malloc(sizeof(TestStruct) * 18);
for (i = 1; i <= 3; i++) {
for (j = 0; j < 6; j++) {
test[i].num = i;
}
}
for (i = 0; i < 18; i++) {
printf("%d ", test[i].num);
}
return 0;
}
If I just call printf() inside a nested for-loop, it works fine:
#include <stdio.h>
int main(void) {
int i, j;
for (i = 1; i <= 6; i++) {
for (j = 0; j < 3; j++) {
printf("%d ", i);
}
}
}
Why is this happening?
test[i]do?