C Pointer problem

Discussion in 'Programming' started by question?, Apr 17, 2008.

  1. #1
    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):
     
    question?, Apr 17, 2008 IP
  2. it career

    it career Notable Member

    Messages:
    3,562
    Likes Received:
    155
    Best Answers:
    0
    Trophy Points:
    270
    #2
    //b-z = c-x
    Recompile and run.
     
    it career, Apr 18, 2008 IP
  3. Rukna

    Rukna Peon

    Messages:
    80
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    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.:confused:
     
    Rukna, Apr 18, 2008 IP
  4. question?

    question? Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    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.
     
    question?, Apr 20, 2008 IP
  5. Swizznezz

    Swizznezz Peon

    Messages:
    29
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    surprise..

    malloc(sizeof(pointer)) = 4bytes

    malloc(sizeof(notapointer)) = size of the struct
    malloc(sizeof(struct vec3)) = size of the struct
     
    Swizznezz, Apr 22, 2008 IP