struct pointers inside structures

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sajet
    New Member
    • Nov 2008
    • 3

    struct pointers inside structures

    i have two structures

    Code:
    struct glb_tab{
            int thread_id;
            struct inode_info *q;
    
    };
    struct inode_info{
            int size;
            int free_mem;   
            int arr[8];
    };
    
    struct glb_tab *p;
                  p = (struct glb_tab *)malloc(sizeof *p);
    struct inode_info *q;
            q = (struct inode_info *)malloc(sizeof *q);
    i want to access contents of q

    for eg
    p->q->size;

    how to access size in the above mentioned way.......

    thanks
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Have a look at this thread for an answer.

    kind regards,

    Jos

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      Please use [code]...[/code] tags round your code if you are posting more than 1 or 2 lines.

      I think your problem is that you want to access p->q->size but
      struct inode_info *q;
      q = (struct inode_info *)malloc(sizeof *q);

      Actually creates a whole new variable q and allocates it and doesn't allocate anything to p->q.

      Try this instead
      p->q = malloc(sizeof *p->q);

      Note I removed the cast, if you are using C the cast should be unnecessary, and in fact can cover up errors. I often see casts covering up code errors where the programmer has put in the cast to make the compiler warning go away rather than fix the error in the code.

      On the other hand if you are using C++ you should be using the new operator.
      p->q = new inode_info;

      Comment

      • sajet
        New Member
        • Nov 2008
        • 3

        #4
        i found out the solution

        last line has to be changed

        p->q = (struct inode_info *)malloc(sizeof *q);

        this is working


        anyways thanks for the reply.....i'm starting to like here.....i'll be active member of this community

        Comment

        Working...