# Self-Referential Structures

Lets say we want to create a structure to store the data of an employee. The following structure has the members to store some basic data about an employee.

```c
struct employee {
 char firstName[20];
 char lastName[20];
 int age;
 double Salary;
};
```

Additionally, each employee has a manager. The manager in turn has a higher level manager, and this continues up the organizational hierarchy levels.

The manager is also an employee so it makes sense to use the `struct employee` to store manager data as well.

A struct type may not contain a variable of its own struct type, it results in a compilation error.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1711361939300/4b14c497-bbba-4814-baba-7d45ac3cd6b2.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1711362000076/91a02810-5da9-44d3-ae8f-ec1210dd9eb0.png align="center")

But a struct may contain a pointer to its own struct type. For example, the updated `struct employee` below contains a pointer to the employee’s `manager`, which would be another `struct employee` object:

```c
struct employee { 
    char firstName[20];
    char lastName[20];
    unsigned int age;
    double hourlySalary;
    struct employee *managerPtr; // pointer 
};
```

A structure containing a member that’s a pointer to the same struct type is a ***self-referential structure***. Self-referential structures are used to build linked data structures, which in this case is the organizational structure or the chain of command.

```c
#include <stdio.h>
struct employee {
    char firstName[20];
    char lastName[20];
    unsigned int age;
    double hourlySalary;
    struct employee *managerPtr; // pointer
};
int main() {
  // Declare two employee variables
  struct employee emp1, emp2;

  // Assign values to emp1
  strcpy(emp1.firstName, "John");
  strcpy(emp1.lastName, "Doe");
  emp1.age = 30;
  emp1.hourlySalary = 25.50;

  // Set emp1's manager to NULL (initially unknown)
  emp1.managerPtr = NULL;

  // Assign values to emp2 (assuming emp2 is emp1's manager)
  strcpy(emp2.firstName, "Jane");
  strcpy(emp2.lastName, "Smith");
  emp2.age = 40;
  emp2.hourlySalary = 30.00;

  // Set emp1's manager to point to emp2
  emp1.managerPtr = &emp2;

  // Print employee information
  printf("Employee 1: %s %s (Age: %u, Hourly Salary: %.2f)\n",
         emp1.firstName, emp1.lastName, emp1.age, emp1.hourlySalary);

  // Check if manager is assigned (assuming a manager has a non-NULL pointer)
  if (emp1.managerPtr != NULL) {
    printf("Employee 1's manager: %s %s\n",
           emp1.managerPtr->firstName, emp1.managerPtr->lastName);
  } else {
    printf("Employee 1's manager not assigned yet.\n");
  }

  return 0;
}
```

Output:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1711363890557/6a8612c3-d280-45c0-86a4-9d321a63c20d.png align="center")
