Skip to main content

Command Palette

Search for a command to run...

Self-Referential Structures

Updated
2 min readView as Markdown
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.

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.

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:

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.

#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:

32 views

More from this blog

P

Programming Tutorials

89 posts