help with struct and pointers

Ok this is my situation I have this header file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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:

1
2
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!!!
fat *pfat;

Here, you have made a pointer to a fat object. That fat object does not exist because you have not made it. You have made a pointer. When you make a pointer to something, you still have to make the actual something and then make the pointer actually point to that something.

fat aFat;

This code makes an actual object of type fat, called aFat. The newly created fat object contains an int called files, an int called dirs, and a pointer to an object of type dir... but that object does not yet exist. I have not made it. I have only made a pointer to it, and right now it doesn't point at a dir object. It will be pointing at some random piece of memory.

Do you understand this? That a pointer to an object, and the object itself, are two distinct things and making a pointer does not automatically create the thing you want it to point to.

Then how do I make it to point correctly?
closed account (zwA4jE8b)
fat *pfat = new fat;

This declares pfat to be a pointer (4 byte integer) to a fat object.
new allocates memory on the heap, sizeof fat.
= assigns the address of this newly allocated memory to pfat

or to reference moschops reply:

1
2
3
fat *pfat;
fat aFat;
pfat = &aFat;
Last edited on
Ok got it. I did the following:
1
2
3
        fat *fatito = new fat;
	fatito->dir_array = new dir[10];
	fatito->dir_array[0].root_dir = 0;
Don't forget to delete fat at some point, or your program will get too heavy and make your computer run slowly.

http://www.cplusplus.com/doc/tutorial/pointers/
http://www.cplusplus.com/doc/tutorial/dynamic/
Topic archived. No new replies allowed.