0% found this document useful (0 votes)
17 views

Lec08-Struct Union Linked List

Uploaded by

v.priovag
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Lec08-Struct Union Linked List

Uploaded by

v.priovag
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Computer Systems programming

Lecture #8: Struct (Cont’d), Union, Linked List

Cuong Do

3/25/2023 Systems programming 1


Overview

▪ Struct (Cont’d)
▪ Union
▪ Linked-list

3/25/2023 Systems programming 2


Struct example: Student info
#include <stdio.h>
#include <string.h>

struct Student
{
char name[50];
char Major;
int year;
};

// pass by value
void printStudent(struct Student var) {

printf("Student name : %s\n", var.name);


printf("Student major : %c\n", var.major);
printf("Student year : %d\n", var.year);
}

3/25/2023 Systems programming 3


Cont’d
(Continued)

// pass by reference
void changeStudent(struct Student* var)
{
var->year = 21;
var->major = ‘EE';
}

int main(){
struct Student student1 = {“Elon Musk", ‘ME’, 22}; // initialising the object

// passing by value
printStudent(student1);
// passing by reference Output:
changeStudent(&student1); Student name : Elon Musk
Student section : ME
return 0; Student class : 22
}

3/25/2023 Systems programming 4


list
struct item {
char *s;
struct item *next;
}
▪I.e., an item can point to another item
▪… which can point to another item
▪… which can point to yet another item
▪… etc.
Thereby forming a list of items

3/25/2023 Systems programming 5


A note about structs and pointers

▪ The following is legal:–


/* in a .c or .h file */ Called an opaque type!
struct item; Program can use pointers to items
but cannot see into items.
struct item *p, *q; Cannot define any items, cannot
malloc any items, etc.
… /* In another file */
struct item {
int member1; Implementer of item can change
float member2; the definition without forcing
struct item *member3; users of pointers to change their
}; code!

3/25/2023 Systems programming 6


Another note about structs

▪ The following is not legal:–


struct motor {
float volts;
float amps;
float rpm;
unsigned int phases;
}; //struct motor

motor m;
You must write
struct motor m;
motor *p; struct motor *p;

3/25/2023 Systems programming 7


Typedef

▪ Definition:– a typedef is a way of renaming a type


▪ E.g.,
typedef struct motor Motor;

Motor m, n; E.g., typedef, lets you


Motor *p, r[25]; leave out the word “struct”
Motor function(const Motor m; …);

3/25/2023 Systems programming 8


typedef (continued)

▪typedef may be used to rename any type


▪ Convenience in naming
▪ Clarifies purpose of the type Very common in C and C++
▪ Cleaner, more readable code
Esp. for portable code!
▪ Portability across platforms
▪E.g., These three may change from
▪ typedef int size_t; platform to platform
▪ typedef long int32;
▪ typedef long long int64; Defined once in a .h file!

3/25/2023 Systems programming 9


Revisit note about structs and pointers

▪ The following is legal:–


/* in a .c or .h file */
typedef struct _item Item;
Item *p, *q;

… /* In another file */
struct _item {
char *info;
Item *nextItem;
};

3/25/2023 Systems programming 10


Conclusion
• Structure in C is a user-defined data type. It binds the two or
more data types or data structures together.
• The Structure is created using struct keyword and its variables are
created using struct keyword and structure name.
• A data type created using structure in C can be treated as other
primitive data types of C to declare a pointer for it, pass it as a
function argument, or return from the function.
• There are three ways to initialize the structure variables: using the
dot operator, using curly braces, or designated initialization.
• One structure can consist of another structure, or more means
there can be nested Structures.
• With the help of typedef, we can give short or new names to a
structure data type. designated example:

int a[6] = {[4] = 29, [2] = 15 }; or


int a[6] = {[4]29 , [2]15 };

3/25/2023 Systems programming 11


Unions

▪A union is like a struct, but only one of its members is


stored, not all
▪ A union can have numerous members, but only one of them
can occupy the memory at any one moment. Unions allow
developers to optimize memory usage while declaring
variables.
▪E.g.,
union {
int ival;
float fval;
char *sval;
} u;

3/25/2023 Systems programming 12


Unions (continued)
▪It is programmer’s responsibility to keep track of which
type is stored in a union at any given time!

#include <stdio.h>

struct Area
{
//Anonymous union
union
{
int radius;
int height;
};
};

int main()
{
struct Area r, h;
r.radius = 15;
use 2 separate struct
h.height = 10;
int area;

area = (2 * 3.14 * r.radius * h.height) + (2 * 3.14 * r.radius * r.radius);


printf("The Area of the cylinder is: %d units", area);

return 0;
}

3/25/2023 Systems programming 13


Example of Union vs. Struct
#include <stdio.h>
union unionFoodCost
{
//defining a union char: -> 1 byte
char name[32]; float: -> 4byte In unions, all members share the same
int: -> 4 byte
Float cost; memory, and the size of memory assigned is
int fid; equal to the largest member. Here in uFood,
} uFood;
the name has the largest size (32 bytes). Hence
struct structFoodCost
the size of the entire union is 32 bytes.
{
char name[32];
float cost;
int fid;
} sFood;

int main() Output


{
printf("size of union = %d bytes", sizeof(uFood)); size of union = 32
printf("\nsize of structure = %d bytes", sizeof(sFood)); size of structure = 40
return 0;
}

3/25/2023 Systems programming 14


Difference between Struct and Union
• Altering the members' values in the struct will not affect the
other members. However, altering members' values in unions
will affect the other members.
• In structures, every member is assigned a unique memory
location, whereas, in unions, all the data members share a
memory location.
• In structures, individual members can be accessed at any time.
In unions, however, only one member can be accessed
simultaneously.
• In structures, several or all members can be initialized at once.
However, in unions, only the first union member can be
initialized.
can only initialize the 1st, the others want to change -> have to use assignment

3/25/2023 Systems programming 15


Unions (continued)

▪unions are used much less frequently than structs —


mostly
▪in the inner details of operating system
▪in device drivers
▪in embedded systems where you have to access
registers defined by the hardware

3/25/2023 Systems programming 16


Break time
▪ a = 10;
▪ b = 20;

Let’s write a C program to swap a and b values without using any


other variable.

▪ a = 20;
▪ b = 10;
#include <stdio.h>
#include <conio.h>
int main() {
int a=10, b=20;
return 0;
}

3/25/2023 Systems programming 17


Linked List
Common Data Structures in C and C++
▪Linked lists
▪ One-way
▪ Doubly-linked
▪ Circular
▪Trees
▪ Binary
▪ Multiple branches
▪Hash Tables
▪ Combine arrays and linked list
▪ Especially for searching for objects by value

3/25/2023 Systems programming 19


Definitions
▪Linked List
▪ A data structure in which each element is dynamically allocated
and in which elements point to each other to define a linear
relationship
▪ Singly- or doubly-linked
▪ Stack, queue, circular list
▪Tree
▪ A data structure in which each element is dynamically allocated
and in which each element has more than one potential
successor
▪ Defines a partial order

3/25/2023 Systems programming 20


Linked List

struct listItem {
type payload;
struct listItem *next;
}; payload
next

payload
next
payload
payload next
next
Linked List (continued)
▪Items of list are usually same type
▪ Generally obtained from malloc()
▪Each item points to next item
▪Last item points to null
▪Need “head” to point to first item!

▪“Payload” of item may be almost anything


▪ A single member or multiple members
▪ Any type of object whose size is known at compile time
▪ Including struct, union, char * or other pointers
▪ Also arrays of fixed size at compile time (see p. 214)

3/25/2023 Systems programming 22


Usage of Linked Lists
▪Not massive amounts of data
▪ Linear search is okay
▪Sorting not necessary
▪ or sometimes not possible
▪Need to add and delete data “on the fly”
▪ Even from middle of list
▪Items often need to be added to or deleted from
the “ends”

3/25/2023 Systems programming 23


Linked List (continued)

struct listItem {
type payload;
struct listItem *next;
};
struct listItem *head;
payload
payload next
next
payload
payload
next
next
Adding an Item to a List

struct listItem *p, *q;


▪Add an item pointed to by q after item pointed to by p
▪ Neither p nor q is NULL

payload
next
payload
payload
next
next
payload
payload
next
next
Adding an Item to a List

listItem *addAfter(listItem *p, listItem *q){


q -> next = p -> next;
p -> next = q;
return p;
}

payload
next payload
payload
next
next
payload
payload
next
next
Adding an Item to a List

listItem *addAfter(listItem *p, listItem *q){


q -> next = p -> next;
p -> next = q;
return p;
}

payload
next payload
payload
next
next
payload
payload
next
next
Adding an Item to a List
Question: What to do if we cannot
guarantee that p and q are non-NULL?
listItem *addAfter(listItem *p, listItem *q){
q -> next = p -> next;
p -> next = q;
return p;
}

payload
next payload
payload
next
next
payload
payload
next
next
Adding an Item to a List (continued)

listItem *addAfter(listItem *p, listItem *q){


if (p && q) {
q -> next = p -> next;
p -> next = q;
}
return p;
}
payload
next payload
payload
next
next
payload
payload
next
next
What about Adding an Item before another
Item?
struct listItem *p;
▪Add an item before item pointed to by p (p != NULL)

payload
next
payload
payload
next
next
payload
payload
next
next
What about Adding an Item before another Item?
▪ Answer:–
▪ Need to search list from beginning to find previous item
▪ Add new item after previous item

▪ This is needed in PA#3


▪ Insert item after earlier event times and before later ones
▪ Need to search the list

3/25/2023 Systems programming 31


Doubly-Linked List

struct listItem {
type payload;
listItem *prev;
listItem *next;
};
struct listItem *head, *tail;

payload payload
prev next prev next payload
payload prev next
prev next
Other Kinds of List Structures
▪Queue — FIFO (First In, First Out)
▪ Items added at end
▪ Items removed from beginning
▪Stack — LIFO (Last In, First Out)
▪ Items added at beginning, removed from beginning
▪Circular list
▪ Last item points to first item
▪ Head may point to first or last item
▪ Items added to end, removed from beginning

3/25/2023 Systems programming 33


Optional:–
Circular List
struct listItem *head;

struct listItem *tail;

payload
payload
next
next
payload
payload
next
next

listItem *addAfter (listItem *p, listItem *tail){


if (p && tail) {
p -> next = tail -> next;
tail = p;
} else if (p) {
tail p -> next = p;
}
return tail;
}
Application of Linked List in the real world
1.Image viewer – Previous and next images are linked and can be accessed
by the next and previous buttons.
2.Previous and next page in a web browser – We can access the previous
and next URL searched in a web browser by pressing the back and next
buttons since they are linked as a linked list.
3.Music Player – Songs in the music player are linked to the previous and
next songs. So you can play songs either from starting or ending of the
list.
4.GPS navigation systems- Linked lists can be used to store and manage a
list of locations and routes, allowing users to easily navigate to their
desired destination.
5.Robotics- Linked lists can be used to implement control systems for
robots, allowing them to navigate and interact with their environment.
6.Task Scheduling- Operating systems use linked lists to manage task
scheduling, where each process waiting to be executed is represented as a
node in the list
7.……..

3/25/2023 Systems programming 35

You might also like