help with structs and pointers in C++

Discussion in 'C++' started by ctrlaltcasper, May 25, 2011.

  1. ctrlaltcasper

    ctrlaltcasper New Member

    Joined:
    May 25, 2011
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Ok this is my situation I have this header file:
    Code:
    struct dir 
    { 
       char name[3]; 
       int root_dir; 
       int has_children; 
       int num_children; 
       int offset_to_children[2]; 
       int offset_to_files[16]; 
    }; 
    struct files 
    { 
       char name[5]; 
       int size; 
       int offset_to_beginning; 
       int has_fragment; 
       int next_fragment; 
    }; 
    struct fat 
    { 
       int files;  
       int dirs;  
       struct dir *dir_array;  
       struct files *file_array;  
    };
    In my program if I want to access the struct fat member *dir_array or *file_array, given that this member are pointers to another struct how can I access this members from my main program? This is what I'm doing and it compiles:
    Code:
    fat *pfat; 
    pfat->dir_array->root_dir=0;
    My doubt is if I'm doing it right. Can anybody clarify my doubt and point my to the right direction. Thanks!!!
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    fat *pfat declares pfat as a pointer to a fat. Note that it DOES NOT create anything for it to point to, so if this is really what you're doing without any intermediate code (that creates the memory structures) then it will compile but you have a memory corruption, because pfat itself doesn't exist, therefore pfat->dir_array is meaningless, as is pfat->dir_array->root_dir. So what these two lines of code will do is to write a zero to some random byte of memory, the effects of which will be determined by what that memory is subsequently used for.
     
  3. Chong

    Chong New Member

    Joined:
    May 15, 2011
    Messages:
    29
    Likes Received:
    7
    Trophy Points:
    0
    Hi
    try the following:
    +++++++++++++++++++++
    struct dir {
    char name[100];
    int root_dir;
    :
    };
    struct fat {
    struct dir*dir_away;
    };

    main()
    {
    fat *pFat = new struct fat[1];
    pFat->dir_array = new struct dir[1];
    pFat->dir_array->root_dir = 1;
    }
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice