Structures in C

Structure groups variables of different types.

Example:

struct Person {
    int age;
    char grade;
};

Declaring and using

struct Person p1;
p1.age = 10;
p1.grade = 'A';

Dot vs Arrow

struct Person *ptr = &p1;
printf("%d", ptr->age);

Initialization

struct Person p2 = {10,'A'};

Designated init:

struct Person p3 = {.grade='B', .age=20};

Passing struct

By value:

void f(struct Person p);

By pointer (recommended):

void f(struct Person *p);

typedef

typedef struct Person {
    int age;
    char grade;
} Person;

Shallow vs Deep copy (important)

If struct contains pointer:

typedef struct {
    char *name;
    int age;
} Emp;

Copying:

Emp e2 = e1;

Only pointer copied → shallow copy.

Need deep copy manually (malloc + strcpy).


Self referential struct

Used in linked list:

typedef struct Node{
    int data;
    struct Node *next;
} Node;