Structures Combining data types into a logical groupings.

Slides:



Advertisements
Similar presentations
Programming in C Chapter 10 Structures and Unions
Advertisements

C Language.
C Structures and Memory Allocation There is no class in C, but we may still want non- homogenous structures –So, we use the struct construct struct for.
Structures Spring 2013Programming and Data Structure1.
Structures in C.
Data Types C built-in data types –char, int, float, double, int*, etc. User-defined data types: the programmer can define his/her own data types which.
CSC141- Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 25 Thanks for Lecture Slides: Dr. Sadaf Tanveer Dr. Sadaf Tanveer,
POINTER Prepared by MMD, Edited by MSY1.  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference.
Structures. An array allows us to store a collection of variables However, the variables must be of the same type to be stored in an array E.g. if we.
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
Introduction to C Programming CE Lecture 10 Data Structures typedef and struct.
Programming C/C++ on Eclipe Trình bày : Ths HungNM C/C++ Training.
Chapter 11 Structure. 2 Objectives You should be able to describe: Structures Arrays of Structures Structures as Function Arguments Dynamic Structure.
Chapter 11: Structured Data. Slide Introduction An array makes it possible to access a list or table of data of the same data type by using a single.
Operator Overloading and Type Conversions
Structs. Structures We already know that arrays are many variables of the same type grouped together under the same name. Structures are like arrays except.
Pointers CS362. Pointers A Pointer is a variable that can hold a memory address Pointers can be used to: Indirectly reference existing variables (sometimes.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
DCT1063 Programming 2 CHAPTER 5 ADVANCED DATA TYPE (part 1) Mohd Nazri Bin Ibrahim Faculty of Computer Media and Technology TATi University College
Arrays in C++ Numeric Character. Structured Data Type A structured data type is a type that stores a collection of individual components with one variable.
Advanced Data types and Sorting
Lecture 5: Arrays A way to organize data MIT AITI April 9th, 2005.
Cosc237/structures1 Structures aggregate data types record - single variable name for the whole collection composed of several variables - fields,BUT,
計算機程式語言 Lecture 13-1 國立臺灣大學生物機電系 13 Structures.
CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2013 CMPE-013/L Structures Gabriel Hugh Elkaim Spring 2013.
CHAPTER 5 FUNCTIONS I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 11 Structured Data.
Learners Support Publications Classes and Objects.
Chapter 8: Arrays and Functions Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills
COP Structures Instructor: Diego Rivera-Gutierrez I’m back baby!
1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic.
1 Pointers to structs. 2 A pointer to a struct is used in the same way as a pointer to a simple type, such as an int. Pointers to structs were introduced.
1 Chapter 11 Structured Data. 2 Topics 10.1 Abstract Data Types 10.2 Combining Data into Structures 10.3 Accessing Structure Members 10.4 Initializing.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 11: Structured Data.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Spring 2005, Gülcihan Özdemir Dağ Lecture 11, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 11 Outline 11.1.
Copyright © 2012 Pearson Education, Inc. Chapter 11: Structured Data.
Engineering Problem Solving with C Fundamental Concepts Chapter 7 Structures.
 Structures are like arrays except that they allow many variables of different types grouped together under the same name. For example you can create.
Structured Data Types struct class Structured Data Types array – homogeneous container collections of only one type struct – heterogeneous data type.
A FIRST BOOK OF C++ CHAPTER 16 DATA STRUCTURES. OBJECTIVES In this chapter, you will learn about: Single Structures Arrays of Structures Structures as.
Chapter 13: Structures. In this chapter you will learn about: – Single structures – Arrays of structures – Structures as function arguments – Linked lists.
Welcome to Concepts of Pointers. Prepared by:- Sumit Kumar PGT(Computer Science) Kv,Samba.
CSEB 114: PRINCIPLE OF PROGRAMMING Chapter 7: Pointers.
© Oxford University Press All rights reserved. CHAPTER 8 STRUCTURES.
+ Structures and Unions. + Introduction We have seen that arrays can be used to represent a group of data items that belong to the same type, such as.
Pointers *, &, array similarities, functions, sizeof.
Chapter 7: Arrays. Outline Array Definition Access Array Array Initialization Array Processing 2D Array.
CSEB 114: PRINCIPLE OF PROGRAMMING Chapter 7: Pointers.
Programming Fundamentals1 Chapter 6 FUNCTIONS AND POINTERS.
Introduction to Computers and Programming Class 24 Structures (structs) Professor Avi Rosenfeld.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
1 11/30/05CS150 Introduction to Computer Science 1 Structs.
STRUCTURES. INTRODUCTION A structure is same as that of records. It stores related information about an entity. Structure is basically a user defined.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
13/10/2016CS150 Introduction to Computer Science 1 Multidimensional Arrays  Arrays can have more than one column  Two dimensional arrays have two columns.
Chapter 11 Structures, Unions and Typedef 11.1 Structures Structures allow us to group related data items of different types under a common name. The individual.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
CO1401 Program Design and Implementation
Chapter 10-1: Structure.
TMF1414 Introduction to Programming
Pointers.
User-Defined Functions
Lecture 9 Structure 1. Concepts of structure Pointers of structures
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Derived types.
Classes and Objects.
Structures In C Programming By Rajanikanth B.
Data Structures and Algorithms Introduction to Pointers
Structures Structured Data types Data abstraction structs ---
Presentation transcript:

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.

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 ; } ;

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.

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.

Declaring Structures Syntax To declare the template struct template_name { typemember_1 ; typemember_2 ; typemember_3 ; typemember_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.

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.

Declaring Structures These may be combined to form the one statement. struct template_name { typemember_1 ; typemember_2 ; typemember_3 ; typemember_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.

Declaring Structures An 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

Declaring Structures An Example OR in a single statement 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 } card1, card2 ; This is used like a data type. Variable names

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.

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 field number=5 brand=“River” rating=“Weak” Result:beer.numbers=5 beer.brand=“River” beer.rating=“Weak”

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.

Example Program to find the magnitude of a complex value #include int main(void) { /* declare structure template */ struct complex { floatreal ;/* real component */ floatim ;/* imaginary component */ } ; struct complex f ;/* structure variable */ floatmagn ;/* magnitude is  Re 2 + Im 2 */

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) ; }

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.

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

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

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); }

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

Example a structure to keep track of books borrowed #include int main(void) { struct date { int day, month, year ; } ; struct lend { int id ; char book[80] ; struct date lend_date ; } ; struct lend lender ;

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); }

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) ;

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) ;

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) ;

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 declared globally. * shows that it is a pointer

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 ( ).

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.

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 ;

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) ;

Example An example program to calculate net pay for an employee. #include /* 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 *) ;

Example (continued) int main(void ) { struct employee emp = {6782, 8.93, 40.5}; double net_pay; /* pass copies of the values inemp */ 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); }

Another Example Program to illustrate returning a structure pointer from a function. #include /* declare a global template so that it is known by all functions */ struct employee { intid_num; doublepay_rate; doublehours; } ; /* function prototypes */ struct employee * get_vals(struct employee *);

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) ; }

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); }

Another Example Output 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

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.

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.

Defining Data Types Examples // 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 */

Defining Data Types Examples typedef struct stock components ; components part_record ;/* declaration */ typedef struct book * library ; library catalogue ;/* declaration */ This is a typedef for a structure pointer with a template called book. This is a typedef for a structure with a template called stock.