Can anybody please tell me why this code prints "9 5 2"? I am am really frustrated about this. So your help is very appreciated... #include <stdlib.h> #include <stdio.h> struct vec3{ double x, y, z; }; typedef struct vec3 * ps_vec3; int main(){ char i; ps_vec3 a; ps_vec3 b; ps_vec3 c; if((a = (ps_vec3) malloc(sizeof(ps_vec3))) == NULL){ exit(1); } if((b = (ps_vec3) malloc(sizeof(ps_vec3))) == NULL){ exit(1); } if((c = (ps_vec3) malloc(sizeof(ps_vec3))) == NULL){ exit(1); } //b-z = c-x b->x = 9; b->y = 5; b->z = 7; c->x = 2; c->y = 77; c->z = 65; printf("%lf %lf %lf", b->x, b->y, b->z); free(a); free(b); free(c); return 0; } Code (markup):
because u do this "b-z = c-x",As a result now b->z have the value of c->x; if u can't solve this prob,then pm me.
b-z = c-x is not the problem since it is commented out. the problem is that memory allocation is the size of a pointer. The amount of memory allocated should be the size of the struct, not the pointer.
surprise.. malloc(sizeof(pointer)) = 4bytes malloc(sizeof(notapointer)) = size of the struct malloc(sizeof(struct vec3)) = size of the struct