C - Structure Structure Pointers


Consider the following code:

typedef struct Dog Dog;            // Define Dog as a type name

struct Dog                           // Structure type definition
      int age;
      int height;
      char name[20];
      char father[20];
      char mother[20];

The following code shows how to create a pointer for Dog structure type.

Dog *pdog = NULL;

This declares a pointer, pdog, that can store the address of a structure of type Dog.

Without the typedef, you must write the statement as:

struct Dog *pdog = NULL;

You can set pdog to have the value of the address of a particular structure:

Dog adog = { 3, 11, "A", "B", "C"};
pdog = &adog;

Here pdog points to the adog structure.

The pointer could store the address of an element in the array of dogs:

pdog = &my_dog_array[1];

Now pdog points to the structure my_dogs[1], which is the second element in the my_dogs array.

To display the name member of this structure, you could write this:

printf_s("The name is %s.\n", (*pdog).name);

You could write the previous statement like this:

printf_s("The name is %s.\n", pdog->name );

You don't need parentheses or an asterisk.

Related Topics