CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    May 2011
    Posts
    2

    Question help with structs and pointers in C++

    Ok this is my situation I have this header file:
    Code:
    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. #2
    Join Date
    Aug 2008
    Posts
    902

    Re: help with structs and pointers in C++

    If this is C++, then you dont need to declare it struct dir *dir_array, dir *dir_array will suffice.

    Code:
    dir myDir;
    fat *pfat = new fat;
    pfat->dir_array = new dir[number_of_directories];
    pfat->dir_array[0] = myDir;
    I also would suggest using more descriptive names and to avoid abbreviations.

  3. #3
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: help with structs and pointers in C++

    Code:
    fat *pfat;
    pfat->dir_array->root_dir=0;
    It is always incorrect to try to access something through an undefined pointer! You have not directed the pfat pointer at any object yet.

    By the way, this code looks much more like C than C++.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured