Docsity

Data Structures in C: Structs and Linked Lists, Study notes of Computer science

Partial preview of the text

Download Data Structures in C: Structs and Linked Lists and more Study notes Computer science in PDF only on Docsity!

C Dynamic Data Structures

Data Structures

A data structure is a particular organization

of data in memory.

We want to group related items together.

We want to organize these data bundles in a way that is

convenient to program and efficient to execute.

An array is one kind of data structure.

In this chapter, we look at two more:

struct – directly supported by C

linked list – built from struct and dynamic allocation

Defining a Struct

We first need to define a new type for the compiler

and tell it what our struct looks like.

struct flightType {

char flightNum[7]; /* max 6 characters */

int altitude; /* in meters */

int longitude; /* in tenths of degrees */

int latitude; /* in tenths of degrees */

int heading; /* in tenths of degrees */

double airSpeed; /* in km/hr */

This tells the compiler how big our struct is and

how the different data items (“members”) are laid out in memory.

But it does not allocate any memory.

Declaring and Using a Struct

To allocate memory for a struct,

we declare a variable using our new data type.

struct flightType plane;

Memory is allocated,

and we can access

individual members of this

variable:

plane.airSpeed = 800.0;

plane.altitude = 10000;

A struct’s members are laid out

in the order specified by the definition.

plane.flightNum[0]

plane.flightNum[6]

plane.altitude

plane.longitude

plane.latitude

plane.heading

plane.airspeed

typedef

C provides a way to define a data type

by giving a new name to a predefined type.

Syntax:

typedef ;

Examples:

typedef int Color;

typedef struct flightType WeatherData;

typedef struct ab_type {

int a;

double b;

} ABGroup;

Using typedef

This gives us a way to make code more readable

by giving application-specific names to types.

Color pixels[500];

Flight plane1, plane2;

Typical practice:

Put typedef’s into a header file, and use type names in

main program. If the definition of Color/Flight

changes, you might not need to change the code in your

main program file.

Array of Structs

Can declare an array of structs:

Flight planes[100];

Each array element is a struct (7 words, in this case).

To access member of a particular element:

planes[34].altitude = 10000;

Because the [] and. operators are at the same precedence,

and both associate left-to-right, this is the same as:

(planes[34]).altitude = 10000;

Pointer to Struct

We can declare and create a pointer to a struct:

Flight *planePtr;

planePtr = &planes[34];

To access a member of the struct addressed by dayPtr:

(*planePtr).altitude = 10000;

Because the. operator has higher precedence than *,

this is NOT the same as:

*planePtr.altitude = 10000;

C provides special syntax for accessing a struct member

through a pointer:

planePtr->altitude = 10000;

Dynamic Allocation

Suppose we want our weather program to handle

a variable number of planes – as many as the user wants

to enter.

We can’t allocate an array, because we don’t know the

maximum number of planes that might be required.

Even if we do know the maximum number,

it might be wasteful to allocate that much memory

because most of the time only a few planes’ worth of data is

needed.

Solution:

Allocate storage for data dynamically, as needed.

malloc

The Standard C Library provides a function for

allocating memory at run-time: malloc.

void *malloc(int numBytes);

It returns a generic pointer (void*) to a contiguous

region of memory of the requested size (in bytes).

The bytes are allocated from a region in memory

called the heap.

The run-time system keeps track of chunks of memory from the

heap that have been allocated.

Example

int airbornePlanes;

Flight *planes;

printf(“How many planes are in the air?”);

scanf(“%d”, &airbornePlanes);

planes =

(Flight*)malloc(sizeof(Flight) * airbornePlanes);

if (planes == NULL) {

printf(“Error in allocating the data array.\n”);

planes[0].altitude = ...

If allocation fails,

malloc returns NULL.

Note: Can use array notation

or pointer notation.

free

Once the data is no longer needed,

it should be released back into the heap for later use.

This is done using the free function,

passing it the same address that was returned by malloc.

void free(void*);

If allocated data is not freed, the program might run out of

heap memory and be unable to continue.

Linked List vs. Array

A linked list can only be accessed sequentially.

To find the 5

th

element, for instance,

you must start from the head and follow the links

through four other nodes.

Advantages of linked list:

Dynamic size

Easy to add additional nodes as needed

Easy to add or remove nodes from the middle of the list

(just add or redirect links)

Advantage of array:

Can easily and quickly access arbitrary elements

Example: Car Lot

Create an inventory database for a used car lot.

Support the following actions:

Search the database for a particular vehicle.

Add a new car to the database.

Delete a car from the database.

The database must remain sorted by vehicle ID.

Since we don’t know how many cars might be on the lot

at one time, we choose a linked list representation.