40
Structures Combining data types into a logical groupings

Structures Combining data types into a logical groupings

Embed Size (px)

Citation preview

Page 1: Structures Combining data types into a logical groupings

Structures

Combining data types into a logical groupings

Page 2: Structures Combining data types into a logical groupings

Structures

Arrays are used to group information of the same data type together as a single unit. For example, grouping prices together, grouping letters together to form strings, etc.

Structures are used to group information consisting of different data types together as a single unit.

A structure consists of individual elements of different data types which all have a common theme. These elements are grouped together to form a single unit. The individual elements of the structure are called the members of the structure.

Page 3: Structures Combining data types into a logical groupings

Structures

An example of a structure is card describing a book in a library catalogue system. Each card is a structure because it groups different types of information together.

index card

book title

author’s name

call sign

publication date

ISBN number

copies in library

struct index_card{char title[128] ;char author[80] ;char call_sign[20] ; char pub_date[9] ; long int isbn ;int copies ; } ;

Page 4: Structures Combining data types into a logical groupings

Declaring Structures A structure is a derived data type because it consists of other data types.

A structure is a variable and must be declared like any other variable.

The declaration for a structure has two parts. Template Declaration

The structure template defines the data types and the name of the members that make up the structure.

The structure declaration assigns a variable to be of the structure type. This means that the compiler allocates a block of memory large enough to hold the all the members contained in the structure. The variable name refers to the structure.

Page 5: Structures Combining data types into a logical groupings

Declaring Structures

The structure template can be thought of as a data type. This means that it can be used in the declaration for a structure variable. Note that the variable created will be of the type given in the template.

The template for the structure must come before the variable declaration.

The template need only be defined once.

Page 6: Structures Combining data types into a logical groupings

Declaring Structures Syntax

To declare the template

struct template_name

{

type member_1 ;

type member_2 ;

type member_3 ;

type member_n ;

} ; where

template_name is the name of the template structure declared earlier. type is the data type of the structure’s member. member_? is the name of the member. The member can be any valid

C variable, eg char, int, float, double, arrays, other structures etc.

Page 7: Structures Combining data types into a logical groupings

Declaring Structures

To create a structure variable of the template type.

struct template_name var_name ;

where template_name is the name of the template structure

declared earlier. var_name is the name of the structure variable.

Page 8: Structures Combining data types into a logical groupings

Declaring Structures These may be combined to form the one statement.

struct template_name

{

type member_1 ;

type member_2 ;

type member_3 ;

type member_n ;

} var_name ;

where template_name is the name of the template structure declared earlier. type is the data type of the structure’s member. member_? is the name of the member. The member can be any valid

C variable, eg char, int, float, double, arrays, other structures etc. var_name is the name of the structure variable.

Page 9: Structures Combining data types into a logical groupings

Declaring StructuresAn Example

struct index_card{char author[80] ; /* authors name (string) */char title[128] ; /* book title (string) */char call_sign[20] ; /* call sign eg QA763.I2 */char pub_date[9] ; /* publication date dd/mm/yy*/

long int isbn ; /* ISBN number 10 digits */int copies ; // number of copies bought by library} ;/* declare like an ordinary variable*/struct index_card card1, card2 ;

This is used like a data type.

Variable names

Page 10: Structures Combining data types into a logical groupings

Declaring StructuresAn Example

OR in a single statementstruct index_card

{

char author[80] ; // authors name (string)

char title[128] ; // book title (string)

char call_sign[20] ; // call sign eg QA763.I2

char pub_date[9] ; // publication date dd/mm/yy

long int isbn ; //ISBN number 10 digits

int copies ; // number of copies bought by library

} card1, card2 ;

This is used like a data type.

Variable names

Page 11: Structures Combining data types into a logical groupings

Initialising Structures

Since structures are variables they can be initialised in the declaration statement.

Usually a structure is made up of more than one member. This means that the structure is a compound data type. Therefore the initialisation must be done between { } with a comma between each member being initialised.

Each member in the structure must be initialised.

Page 12: Structures Combining data types into a logical groupings

Initialising Structures

An example in a market survey on different beers

struct survey

{

int number ; // number of beers in test

char brand[80] ; // type of beer */

char rating[80] ; // rating of the beer

}

struct survey beer = { 5, “River", "Weak" } ;Initialising each fieldnumber=5

brand=“River”rating=“Weak”

Result: beer.numbers=5

beer.brand=“River”

beer.rating=“Weak”

Page 13: Structures Combining data types into a logical groupings

Accessing the members of a structure

Each member of the structure can be accessed individually. To access the variable, the structure and the member need to be identified.

The structure to be accessed is identified by the varaible name. The member in that structure is identified by the member name declared in the template.

The members are used as though they are a varaible of the data type declared. eg copies is used like an int, title is used like a string, etc Syntax

struct_name member

where struct_name is the name of the declared structure variable. member is the name of the member to be accessed.

Page 14: Structures Combining data types into a logical groupings

Example

Program to find the magnitude of a complex value

#include <stdio.h>

#include <math.h>

int main(void)

{

/* declare structure template */

struct complex

{

float real ; /* real component */

float im ; /* imaginary component */

} ;

struct complex f ; /* structure variable */

float magn ; /* magnitude is Re2 + Im2 */

Page 15: Structures Combining data types into a logical groupings

Example (continued)

// read in the member values from the keyboard

scanf(“%g”,&f.real) ;

scanf(“%g”,&f.im) ;

// display the member values

printf(“real = %g\n”,f.real) ;

printf(“im = %g\n”,f.im) ;

// use the member values to calculate the magnitude

magn = sqrt( (f.real * f.real) + (f.im * f.im) ) ;

printf(“magnitude = %g\n”,magn) ;

}

Page 16: Structures Combining data types into a logical groupings

Arrays of structures

It is possible to have an array of structures.

An array of structures is declared with the variable name using square brackets like an ordinary array variable.

Syntax

struct template_name var[size] ;where template_name is the name of the template structure declared

earlier. var is the variable name. size is the number of structures in the array.

Page 17: Structures Combining data types into a logical groupings

Arrays of structures

Each element in the array is a structure. Each structure contains the members declared in the structure’s template.

Each individual structure is accessed using an index. This is the same as accessing any array.

Each member is accessed like an ordinary structure. That is, with a point followed by the member.

var[index] member

Page 18: Structures Combining data types into a logical groupings

Example

#include <stdio.h>

/* construct a global template */struct pay_rec{ long id; char name[20]; float rate;};

Page 19: Structures Combining data types into a logical groupings

Example (continued)

int main(void)

{

int i;

struct pay_rec employee[5] =

{

{ 32479, "Lister, D.", 6.72 },

{ 33623, "Cat, T.", 7.54},

{ 34145, "Krytan, R.", 5.56},

{ 35987, "Rimmer, A.J. ", 5.43 },

{ 36203, "Holly, C.", 8.72 }

} ;

/* display the elements of the structures */

for ( i = 0; i < 5; i++)

{

printf("\n%ld",employee[i].id) ;

printf("\t%s", employee[i].name) ;

printf("\t%.2g", employee[i].rate);

}

}

Page 20: Structures Combining data types into a logical groupings

Structures containing structures

Since a structure is a valid variable it is possible to declare structures that contain structures.

For readability the structure contained in a structure should have its template declared before it is used in a template.

Each member of the structure is accessed in the usual manner. However if the member of the structure is a structure then the second structure can be accessed using a second point followed by the structure name.

struct1 struct2 member

Page 21: Structures Combining data types into a logical groupings

Example a structure to keep track of books borrowed

#include <stdio.h>

#include <string.h>

int main(void)

{

struct date

{

int day, month, year ;

} ;

struct lend

{

int id ;

char book[80] ;

struct date lend_date ;

} ;

struct lend lender ;

Page 22: Structures Combining data types into a logical groupings

Example a structure to keep track of books borrowed (continued)

/* set the data */

lender.id = 1234 ;

strcpy(lender.book, “Ethel the Aardvark goes Quantity Surveying”) ;

lender.lend_date.day = 13 ;

lender.lend_date.month = 10 ;

lender.lend_date.year = 95 ;

/* print the data */

printf(“id = %i\n”,lender.id) ;

printf(“book = %s\n”,lender.book) ;

printf(“date = “) ;

printf(“%d –”,lender.lend_date.day);printf(“%d –”,lender.lend_date.month);printf(“%d\n”,lender.lend_date.year);}

Page 23: Structures Combining data types into a logical groupings

Structures and Functions

Passing Structure Members to Functions Structure members are treated as though they are an independent

variables. The data type of the variable is the data type declared for the member in the structure template.

If the member’s value is to be passed to the function, the structure member needs to be placed in the parameter list of the function when the function is called.

eg

print_day(date.day) ;

Page 24: Structures Combining data types into a logical groupings

Structures and Functions

The function definition should contain in the parameter list a variable of the same data type as the value being passed to the function.

eg

void print_day(int day) ;

The function prototype is similar to the function definition. The parameter list should contain a variable of the same data type as the value to be passed to the function.

eg

void print_day(int) ;

Page 25: Structures Combining data types into a logical groupings

Structures and Functions

Passing Structures to Functions

Functions are a compound data type therefore they are passed to function by their address. This is call by reference.

The template for the structure should be declared globally so that it is known by all the functions.

When calling the function, the address should be passed in the parameter list of the function. The address of the structure is found by using the & (address) operator.

eg

search_for_name(&employee_record) ;

Page 26: Structures Combining data types into a logical groupings

Structures and Functions

The function definition should have a declaration of a structure pointer in the parameter list. This is the pointer name that will contain the address of the structure and thereby allow access to the contents of the structure. The structure pointer contains the declaration of a structure except that the variable name has a * in front of it. The * in the declaration means that this is a pointer.

Example

void search_for_name( struct record *e)

Structure’s name declaredglobally.

* shows thatit is a pointer

Page 27: Structures Combining data types into a logical groupings

Structure Pointers

A structure pointer contains the address of the structure. Each member of the structure pointed to can be found by using

(*struct_ptr) member

The * means access the structure whose address is held in struct_ptr. The parenthesis are used so that this is evaluated first. Once the contents of the structure are found, the structure’s member, which is part of the contents of the structure, can be accessed using the period ( ).

Page 28: Structures Combining data types into a logical groupings

Structure Pointers

Since pointers to structures are commonly used, a shorthand notation has been developed.

struct_ptr -> member

The -> is a minus sign(-) followed by a greater than sign (>).

struct index_card card ={“author”,”title”,”QA12”,”01/02/03”,”456790”,10};

struct index_card *ptr ;

int num ;

ptr = &card ;

num = ptr -> copies ;

Any changes to the value of member, changes that member in the structure passed to the function. In other words, the structure being passed to the function can be changed inside the function.

Page 29: Structures Combining data types into a logical groupings

Structure Pointers

If the structure being passed contains a structure as one of its members then the member structure is accessed using -> .

To access the members of the member structure a period ( ) is used.

This means that the member structure is accessed using -> and its members are accessed using ( ) .

eg

s_ptr -> date.day = 15 ;

Page 30: Structures Combining data types into a logical groupings

Returning a Structure

The structure is passed to the function as a pointer. This means that the pointer should be returned.

To return a structure pointer, the function definition should contain

struct template * function_name(parameter_list) ;

The prototype will be

struct template * function_name(data types of parameter_list) ;

Page 31: Structures Combining data types into a logical groupings

Example An example program to calculate net pay for an employee.

#include <stdio.h>

/*

Global declaration for structure template so that it is known by the functions as well

*/

struct employee

{

int id_num;

double pay_rate;

double hours;

};

/* function prototype */

double calc_net(struct employee *) ;

Page 32: Structures Combining data types into a logical groupings

Example (continued)

int main(void )

{

struct employee emp = {6782, 8.93, 40.5};

double net_pay;

/* pass copies of the values in emp */

net_pay = calc_net(&emp);

printf("The net pay for employee %d is $%6.2lf", emp.id_num, net_pay);

}

/* function definition */

/* pt is a pointer to a structure of employee type */

double calc_net(struct employee *pt)

{

double calc ;

calc = pt->pay_rate * pt->hours ;

return(calc);

}

Page 33: Structures Combining data types into a logical groupings

Another Example

Program to illustrate returning a structure pointer from a function.

#include <stdio.h>

/* declare a global template so that it is known by all functions */

struct employee

{

int id_num;

double pay_rate;

double hours;

} ;

/* function prototypes */

struct employee * get_vals(struct employee *);

Page 34: Structures Combining data types into a logical groupings

Another Example (continued)int main(void){ struct employee emp ; /* structure variable*/ struct employee *ret_emp ; /* pointer to a structure */

/* Fill the structure with data. Return a pointer to the structure that has been filled. */

ret_emp = get_vals(&emp);

/* print out the contents of the structure */ printf("\nThe actual structure changed in the function.") ; printf("\nThe employee id number is %d", emp.id_num) ; printf("\nThe employee pay rate is $%5.2lf", emp.pay_rate) ; printf("\nThe employee hours are %5.2lf", emp.hours) ;

/* print out the contents of the structure pointed to. Note that the structure pointed to will be emp */ printf("\n\nUsing the structure pointer returned by the function.") ; printf("\nThe employee id number is %d", ret_emp->id_num) ; printf("\nThe employee pay rate is $%5.2lf", ret_emp->pay_rate) ; printf("\nThe employee hours are %5.2lf", ret_emp->hours) ;}

Page 35: Structures Combining data types into a logical groupings

Another Example (continued)

/* function used to fill the structure and return a pointer to the structure filled */

struct employee * get_vals(struct employee *e_struct)

{

e_struct->id_num = 6789;

e_struct->pay_rate = 16.25;

e_struct->hours = 38.0;

return(e_struct);

}

Page 36: Structures Combining data types into a logical groupings

Another ExampleOutput

The actual structure changed in the function.

The employee id number is 6789

The employee pay rate is $16.25

The employee hours are 38.0

Using the structure pointer returned by the function.

The actual structure changed in the function.

The employee id number is 6789

The employee pay rate is $16.25

The employee hours are 38.0

Page 37: Structures Combining data types into a logical groupings

Defining Data Types

C allows you to define new data type names for the existing C data types.

By defining the name for a data type it allows the programmer to use names appropriate to the algorithm. This means that the programmer can think and write code in terms of the problem.

The keyword used to create a new definition for a data type is the typedef keyword.

The typedef declaration does not create new data types, it only creates synonyms for the existing data types. This means that it is possible to represent the data type with the user name, the data type is still valid.

Page 38: Structures Combining data types into a logical groupings

Defining Data Types

Syntax:

typedef data_type user_type_name ;

where typedef is the keyword which means type definition user_type_name is the new name you are giving this data

type. data_type is the data type you wish to rename.

When declaring a variable of user_type_name, user_type_name is used instead of the data type before the variables name.

Page 39: Structures Combining data types into a logical groupings

Defining Data TypesExamples

// This now allows the name letter to be used instead of char in a variable declaration. */

typedef char letter ;letter answer ; /* declaration */letter result[10] ; /* declaration */

// allows the name string to be used instead of a char array in a variable declaration

typedef char[SIZE] string ; /* SIZE is given in a #define */

// allows the name vector to be used instead of an int array in a variable declaration

typedef int[10] vector ;vector mass ; /* declaration */

// allows the name ptr to be used instead of an int * in a variable declaration

typedef int *ptr ;ptr x ; /* declaration */

Page 40: Structures Combining data types into a logical groupings

Defining Data TypesExamples

typedef struct stock components ;

components part_record ; /* declaration */

typedef struct book * library ;

library catalogue ; /* declaration */

This is a typedef for a structurepointer with a template called book.

This is a typedef for a structurewith a template called stock.