Structures#

(ch 9)

Structs#

/*struct definition*/
struct card
{
    int pips;
    int suit;
};

struct card c1, c2; /* Variable declaration */

typedef#

c1.pips = 3;
c1.suit = 's';

c2 = c1;

typedef struct card card;

card c3, c4, c5;

typedef: This keyword allows you to create an alias for a type. In this case, it defines card as an alias for struct card.

image.png

Combining structs & typedef#

typedef struct
{
    float re;
    float im;
} complex;

complex a, b;
complex c[100] = {{1.0, -1.0}, {2.0, -2.0}};

Declarations and Assignments#

struct student {
    char grade;        // Grade of the student (e.g., A, B, C)
    char *last_name;   // Last name of the student
    int student_id;    // Student ID number
};

struct student tmp, *p = &tmp;

tmp.grade = 'A';
tmp.last_name = "Verstappen";
tmp.student_id = 9100017;
printf("Grade: %c\n", tmp.grade);
printf("Last Name: %s\n", tmp.last_name);
printf("Student ID: %d\n", tmp.student_id);
printf("Access via Pointer (Grade): %c\n", p->grade);
printf("Access via Pointer (Last Name): %s\n", p->last_name);
printf("Access via Pointer (Student ID): %d\n", p->student_id);
  • struct student tmp: Declares a variable tmp of type struct student.

  • struct student *p = &tmp;: Declares a pointer p that stores the address of the struct tmp.

  • tmp.member: Accesses a member of the struct directly.

  • p->member: Accesses a member of the struct indirectly through a pointer. Equivalent to (*p).member.

Expression Table#

Expression

Equivalent Expression

Value

tmp.grade

p->grade

'A'

tmp.last_name

p->last_name

"Verstappen"

(*p).student_id

p->student_id

9100017

*p->last_name + 1

(*(p->last_name)) + 1

'W' (next char)

*(p->last_name + 2)

(p->last_name)[2]

'r'

Why Store Strings as Pointers in Structs?#

  1. Dynamic Memory Allocation: Using a pointer, the actual string can be allocated dynamically, allowing it to change in size during runtime.

  2. Memory Efficiency: Instead of storing the entire string in the struct (fixed size), only the pointer is stored, which reduces the struct’s size.

  3. Flexibility: Strings can vary in length, and pointers accommodate strings of any length, as long as memory is allocated correctly.

struct student {
    int student_id;
    char *last_name;  // Pointer to a dynamically allocated string
    char grade;
};

/* Dynamically allocate memory for the string*/
s.last_name = malloc(20 * sizeof(char));
if (s.last_name == NULL) {
    printf("Memory allocation failed\n");
    return 1;
}

/* Copy a string into the allocated memory*/
strcpy(s.last_name, "Verstappen");

Passing Structs#

void update(empolyee_data *p) /*a pointer to the original struct is passed*/
{
    prinf("Input the department number : ");
    scanf("% d", &n);
    p->department.dept_no = n;/*the original struct is modified*/
}

empolyee_data e;
update(&e);

Can we pass it by value ?