Programming in C Chapter 10 Structures and Unions

Slides:



Advertisements
Similar presentations
Incomplete Structs struct B; struct A { struct B * partner; // other declarations… }; struct B { struct A * partner; // other declarations… };
Advertisements

1 Chapter 10 - Structures, Unions, Bit Manipulations, and Enumerations Outline 10.1Introduction 10.2Structure Definitions 10.3Initializing Structures 10.4Accessing.
StructuresStructures Systems Programming. Systems Programming: Structures 2 Systems Programming: 2 StructuresStructures Structures Structures Typedef.
StructuresStructures Systems Programming. StructuresStructures Structures Structures Typedef Typedef Declarations Declarations Using Structures with Functions.
Question Bank. Explain the syntax of if else statement? Define Union Define global and local variables with example Concept of recursion with example.
C Programming lecture 2 Beautiful programs Greek algorithms
2007 Pearson Education, Inc. All rights reserved C Structures, Unions, Bit Manipulations and Enumerations.
2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - Structures, Unions, Bit Manipulations, and Enumerations Outline 10.1Introduction 10.2Structure.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Structures –Collections of related.
EASTERN MEDITERRANEAN UNIVERSITY EENG212 ALGORITHMS & DATA STRUCTURES Structures in C.
Chapter 10 C Structures, Unions, Bit Manipulations and Enumerations Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc.
C Structures What is a structure? A structure is a collection of related variables. It may contain variables of many different data types---in contrast.
C Programming Lecture 23 Enumeration Types Structures.
1 Structures. 2 Structure Basics A structure is a collection of data values, called data members, that form a single unit. Unlike arrays, the data members.
1 Structures. 2 Structure Basics A structure is a collection of data values, called data members, that form a single unit. Unlike arrays, the data members.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
Dynamic memory allocation
C Language.
An introduction to pointers in c
Dynamic Memory Allocation in C.  What is Memory What is Memory  Memory Allocation in C Memory Allocation in C  Difference b\w static memory allocation.
Data Structures Using C++ 2E
The C ++ Language BY Shery khan. The C++ Language Bjarne Stroupstrup, the language’s creator C++ was designed to provide Simula’s facilities for program.
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.
Chapter 6 Structures By C. Shing ITEC Dept Radford University.
Chapter 9 Pointers and Dynamic Arrays. Overview 9.1 Pointers 9.2 Dynamic Arrays.
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
Programming and Data Structure
C Structures Basics of structures Typedef. Data Hierarchy Byte –8 bits (ASCII character ‘A’ = ) Field –Group of characters (character string “Fred”)
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
Structures Spring 2013Programming and Data Structure1.
Structures in C.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Kernighan/Ritchie: Kelley/Pohl:
Winter2015 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University C: Advanced Topics.
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 10 - C Structures, Unions, Bit Manipulations,
Structures and Lists (and maybe stacks) Chapters 9-10.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 10 - Structures, Unions, Bit Manipulations, and Enumerations Outline 10.1Introduction 10.2Structure.
'C' Programming With Structure Records Purpose of structures Coding a structure template Defining a new data type Functions which communicate using structures.
Stack and Heap Memory Stack resident variables include:
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
14/3/02 Sudeshna Sarkar, CSE, IIT Kharagpur1 Structures, ADT Lecture 25 14/3/2002.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 10 - C Structures, Unions, Bit Manipulations,
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.
5/3/01 Sudeshna Sarkar, CSE, IIT Kharagpur1 Structures Lecture
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
 2007 Pearson Education, Inc. All rights reserved C Structures, Unions, Bit Manipulations and Enumerations.
Today’s Material Aggregate Data Types: Structures and Unions
Pointers. Pointer Variable Declarations and Initialization Pointer variables – Contain memory addresses as their values – Normal variables contain a specific.
C Lecture Notes 1 Structures & Unions. C Lecture Notes Introduction Structures –Collections of related variables (aggregates) under one name Can.
Chapter 10 Structures, Unions, Bit Manipulations, and Enumerations Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering.
CPT: Types/ Computer Programming Techniques Semester 1, 1998 Objective of these slides: –to look at how new types can be created 6. User-defined.
Structures and Union. Review bitwise operations –you need them for performance in terms of space and time –shifts are equivalent to arithmetics enumeration.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
 2000 Prentice Hall, Inc. All rights reserved Introduction Structures –Collections of related variables (aggregates) under one name Can contain.
StructureStructure. Outline Introduction Structure Definitions Initializing Structures Accessing Members of Structures Using Structures with Functions.
Programming in C Arrays, Structs and Strings. 7/28/092 Arrays An array is a collection of individual data elements that is:An array is a collection of.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
STRUCTURES. INTRODUCTION A structure is same as that of records. It stores related information about an entity. Structure is basically a user defined.
What do I need to Know For My Assignment?. C Pointer Review To declare a pointer, we use the * operator. This is similar to but different from using *
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
User-Written Functions
CS1010 Programming Methodology
C Structures, Unions, and Enumerations
C Structures, Unions, Bit Manipulations and Enumerations
Derived types.
Chapter 9: Pointers and String
Structures.
Presentation transcript:

Programming in C Chapter 10 Structures and Unions

Structures Complex data types can be constructed from fundamental types aggregate variables of different types Example: information about a playing card members struct card { int pips; char suit; } ; struct card c1, c2; Variable declaration: struct card { int pips; char suit; } c1, c2 ; Variables may also be declared in the structure definition:

Structure types The variable type is struct card not just card. Use typedef to define the type card to be equivalent to the type struct card: typedef struct card card now the variable type really is just “card”. card c3, c4, c5; Variable declaration: Alternatively, typedef may be used directly in conjunction with struct without defining the tag name card first: typedef struct { int pips; char suit; } card ; card can now be used as a variable type.

Using structures Structures can contain any C-type, including arrays, pointers or other structures. Initialisation of structures: (similar to arrays) card c3 = {13,’h’}; /* the king of hearts */ Assignment of structures: c2 = c1; assigns to each member of c2 the value of the corresponding member of c1. declares an array (of size 52) of variables of type “card”; the name of the array is “deck”. Arrays of structures: card deck[52]; Accessing members of a structure: c1.pips = 3; c1.suit = ‘s’; members of the structure are accessed with the operator “.” (dot),

Example: Student grades Define the structure first. This would probably go in a separate header file, e.g. “student.h” struct student{ char *last_name; int student_id; char grade; }; Note that here we haven’t yet assigned the space for the string last_name – just for a pointer to it – so we must use calloc or malloc to allocate space for it int main(void) { struct student tmp, class[100]; /*declaration .... tmp.grade = ‘A’; tmp.last_name = “Casanova”; tmp.student_id = 910017; } class[ ] is an array of structures “Casanova” is defined here before compilation. Normally you’d use calloc/malloc. int fail(struct student class[ ]) { int i, cnt = 0;   for (i = 0; i < 100; ++i) cnt += (class[i].grade == ‘F’); return cnt; } Count the failing grades increment the counter if grade is equal to ‘F’

Example: student grades If the size of the class isn‘t known at compile time, dynamic allocation must be used: struct student *class /*... read in number of students n...*/ class = (struct student *) calloc(n,sizeof(struct student)); The variable *last_name within the structure is a pointer, pointing to a string of appropriate length. struct student{ char last_name[MaxSize]; int student_id; char grade; }; Alternatively, a maximum length string could have been defined to hold the names:

Pointers to structures Structures may contain large amounts of data Use pointers to pass structures to functions instead of moving them in memory If a function should modify the contents of a structure: Use pointers to pass structures to functions instead of passing the structure by value. Pointers to structures struct student *p=&tmp; (*p).grade; Accessing a member with a dereferenced pointer use brackets, because . has higher priority than * p->grade; This is so important that an equivalent syntax is provided (saving two keystrokes)

Example: Complex numbers Header file complex.h struct complex { double re; /* real part */ double im; /* imag. part */ }; typedef struct complex complex; #include “complex.h”   void add(complex *a, complex *b, complex *c) /* *a = *b + *c */ { a->re = b->re + c->re; a->im = b->im + c->im; } Function using complex data structure More to come in homework!

Structures as members of structures Structures can contain other structures as members Example: employer’s database struct dept { char dept_name[25]; int dept_no; }; typedef struct { char name[25]; int employee_id; struct dept department; struct address *a_ptr; double salary; ..... } employee_data; Members structures must be defined beforehand, since the compiler must know their size The size of a pointer to a structure is just the size of the address and therefore known. Struct address can be defined later.

Updating structures in functions: method 1 Send structure e down to the function, modify it, and return the modified structure for use in the calling routine: e = update1(e); ..... employee_data update1(employee_data e) { .... printf (“Input the department number: ”); scanf(“%d”, &n); /* now access member of struct-within-struct... */ e.department.dept_no = n; return e; }   Within calling routine, e.g. function main() This involves a lot of copying of structure members down to the function and back again. There’s a better way...

Updating structures in functions: method 2 Passing a pointer to a data structure is more efficient: Within calling routine (e.g. function main() ), to pass address to update function update2(&e); void update2(employee_data *p) { .... printf(“Input the department number: ”); scanf(“%d”, &n); p->department.dept_no = n; ..... } Use -> instead of . to access structure member, because p is a pointer to the structure

Example: Playing poker The program in ....lect9/poker.c is a model of a poker-playing program. It repeatedly shuffles and deals a set of five cards to each of six players, and then calculates the probability that a flush is dealt (i.e. that all five cards are of the same suit). Look at the code, and run it. The probability of a flush (all cards the same suit) is 0.00198... How close does this program come if you run it several times? Note that the card structure in the code uses an enumerated type to define the suit. Note also that deck[52] is an array, and the variable name “deck[52]” is therefore equivalent to a pointer to the start of the array – the whole array of 52 structures is not passed down with each function call that has deck[ ] as an argument!

Union union int_or_float { int i; float f; } typedef union int_or_float { int i; float f; } number; int main(void) { number n; n.i = 4444; printf("i: %10d f: %16.10e\n", n.i, n.f); n.f = 4444.0; return 0; } union int_or_float { int i; float f; }