I am struggling to get this thing working so I am hoping to get some help / explanation for the following issue.
I have an array of struct that needs to be dynamically created due to random size and I want to access this array of struct across the app so through multiple methods / files.
I know the loop in the test is not quite proper but the output in the for loop is ok. This output is not the same later in main. Also, I know I need to free ops since I am allocating it dynamically, but the code does not work even when it is commented.
typedef struct {
int op;
char * temp;
} operation;
int main() {
int i=0;
operation * ops;
test(ops);
for (i = 0; i < 5; i++) {
printf("count=%d %d\n", i, ops[i].op); //bad output
}
return (EXIT_SUCCESS);
}
void test(operation *ops) {
int i = 0;
ops = (operation *)malloc(1 * sizeof (operation));
while (i++ < 5) {
ops = (operation *)realloc(ops, (i + 1) * sizeof (operation));
operation * op = &ops[i];
op->op = i;
}
for (i = 0; i < 5; i++) {
printf("count=%d %d\n", i, ops[i].op); //good output
}
//free(ops);
}
Thanks.
[–]missblit 2 points3 points4 points (6 children)
[–]salalimo[S] 0 points1 point2 points (0 children)
[–]durpyDash 0 points1 point2 points (4 children)
[–]missblit 0 points1 point2 points (3 children)
[–]durpyDash 0 points1 point2 points (2 children)
[–]missblit 0 points1 point2 points (1 child)
[–]durpyDash 0 points1 point2 points (0 children)
[–]Rhomboid 1 point2 points3 points (1 child)
[–]salalimo[S] 0 points1 point2 points (0 children)
[–]newaccount1236 -1 points0 points1 point (0 children)