C structures and unions (Reek, Ch. 10) 1CS 3090: Safety Critical Programming in C.

Slides:



Advertisements
Similar presentations
Chapter 10 C Structures, Unions, Bit Manipulations and Enumerations Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc.
Advertisements

Programming in C Chapter 10 Structures and Unions
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
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.
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.
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Structures, Unions, and Typedefs CIS 1057 Fall Structures, Unions, and Typedefs CIS 1057 Computer Programming in C Fall 2013 (Many slides based on/borrowed.
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Structures, Unions, and Typedefs CS-2301 D-term Structures, Unions, and Typedefs CS-2301 System Programming D-term 2009 (Slides include materials.
Pointer. Warning! Dangerous Curves C (and C++) have just about the most powerful, flexible and dangerous pointers in the world. –Most other languages.
Object References. Objects An array is a collection of values, all of the same type An object is a collection of values, which may be of different types.
Structures and UnionsCS-2301 B-term Structures and Unions CS-2301, System Programming for Non-majors (Slides include materials from The C Programming.
C pointers (Reek, Ch. 6) 1CS 3090: Safety Critical Programming in C.
1 The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into.
Structures, Unions, and Typedefs CS-2303, C-Term Structures, Unions, and Typedefs CS-2303 System Programming Concepts (Slides include materials from.
C arrays (Reek, Ch. 8) 1CS 3090: Safety Critical Programming in C.
S-1 University of Washington Computer Programming I Lecture 18: Structures © 2000 UW CSE.
Pointers CS362. Pointers A Pointer is a variable that can hold a memory address Pointers can be used to: Indirectly reference existing variables (sometimes.
Engineering Computing I Chapter 6 Structures. Sgtructures  A structure is a collection of one or more variables, possibly of different types, grouped.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
1 Homework HW6 due class 22 K&R 6.6 K&R 5.7 – 5.9 (skipped earlier) Finishing up K&R Chapter 6.
CSE 232: C++ pointers, arrays, and references Overview of References and Pointers Often need to refer to another object –Without making a copy of the object.
Cosc237/structures1 Structures aggregate data types record - single variable name for the whole collection composed of several variables - fields,BUT,
Learners Support Publications Classes and Objects.
1 Pointers and Strings Chapter 5 2 What You Will Learn...  How to use pointers Passing arguments to functions with pointers See relationship of pointers.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
CS 31 Discussion, Week 8 Faisal Alquaddoomi, Office Hours: BH 2432, W 4:30-6:30pm, F 12:00-1:00pm.
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 © 2012 Pearson Education, Inc. Chapter 11: Structured Data.
 2007 Pearson Education, Inc. All rights reserved C Structures, Unions, Bit Manipulations and Enumerations.
Homework Finishing up K&R Chapter 6 today Also, K&R 5.7 – 5.9 (skipped earlier)
Copyright © 2012 Pearson Education, Inc. Chapter 11: Structured Data.
Today’s Material Aggregate Data Types: Structures and Unions
The Cn Language over view The Cn language strongly on ANSI C. So if you are familiar with ANCI it is not so tough to deal with Cn language. Basic Data.
Structured Data Chapter 11. Combining Data Into Structures Structure: C++ construct that allows multiple variables to be grouped together Format: struct.
ECE 103 Engineering Programming Chapter 49 Structures Unions, Part 1 Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE.
 Structures are like arrays except that they allow many variables of different types grouped together under the same name. For example you can create.
Data Types Declarations Expressions Data storage C++ Basics.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 13: Data structures in C.
POINTERS.
Structured Programming Approach Module VIII - Additional C Data Types Structures Prof: Muhammed Salman Shamsi.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
11/5/2016CS150 Introduction to Computer Science 1 Announcements  Assignment 6 due on Wednesday, December 3, 2003  Final Exam on Tuesday, December 9,
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 2 – August 23, 2001.
Structures and Union. Review bitwise operations –you need them for performance in terms of space and time –shifts are equivalent to arithmetics enumeration.
STRUCTURES. C structures: aggregate, yet scalar  aggregate in that they hold multiple data items at one time  named members hold data items of various.
Introduction to Computers and Programming Class 24 Structures (structs) Professor Avi Rosenfeld.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
72 4/11/98 CSE 143 Abstract Data Types [Sections , ]
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.
1 11/30/05CS150 Introduction to Computer Science 1 Structs.
CS 31 Discussion, Week 7 Faisal Alquaddoomi, Office Hours: BH 2432, W 4:30-6:30pm, F 12:30-1:30pm.
Announcements Quiz this Thursday 1. Multi dimensional arrays A student got a warning when compiling code like: int foo(char **a) { } int main() { char.
1 Structures & Unions. 2 User-Defined Types C provides facilities to define one’s own types. These may be a composite of basic types ( int, double, etc)
C arrays (Reek, Ch. 8) CS 3090: Safety Critical Programming in C.
Structures, Unions, Enumerations
C Structures, Unions, Bit Manipulations and Enumerations
Student Book An Introduction
C Structures, Unions, Bit Manipulations and Enumerations
Structures and Union.
Arrays and Pointers Reference: Chapter , 4.11 CMSC 202.
Classes and Objects.
Structures, Unions, and Typedefs
Structures and Union.
Java Programming Language
Structures and Union.
Structures, Unions, and Enumerations
Programming Fundamental
Extra C Material Based on material in: The C Programming Language, Second Edition by Brian W. Kernighan and Dennis M. Ritchie. Prentice Hall, Inc., 1988. 
Presentation transcript:

C structures and unions (Reek, Ch. 10) 1CS 3090: Safety Critical Programming in C

C structures: aggregate, yet scalar CS 3090: Safety Critical Programming in C2  aggregate in that they hold multiple data items at one time  named members hold data items of various types  like the notion of class/field in C or C++ – but without the data hiding features  scalar in that C treats each structure as a unit  as opposed to the “array” approach: a pointer to a collection of members in memory  entire structures (not just pointers to structures) may be passed as function arguments, assigned to variables, etc.  Interestingly, they cannot be compared using == (rationale: too inefficient)

Structure declarations CS 3090: Safety Critical Programming in C3  Combined variable and type declaration struct tag {member-list} variable-list;  Any one of the three portions can be omitted struct {int a, b; char *p;} x, y; /* omit tag */  variables x, y declared with members as described: int members a, b and char pointer p.  x and y have same type, but differ from all others – even if there is another declaration: struct {int a, b; char *p;} z; /* z has different type from x, y */

Structure declarations CS 3090: Safety Critical Programming in C4 struct S {int a, b; char *p;}; /* omit variables */  No variables are declared, but there is now a type struct S that can be referred to later struct S z; /* omit members */  Given an earlier declaration of struct S, this declares a variable of that type typedef struct {int a, b; char *p;} S; /* omit both tag and variables */  This creates a simple type name S (more convenient than struct S )

Recursively defined structures CS 3090: Safety Critical Programming in C5  Obviously, you can’t have a structure that contains an instance of itself as a member – such a data item would be infinitely large  But within a structure you can refer to structures of the same type, via pointers struct TREENODE { char *label; struct TREENODE *leftchild, *rightchild; }

Recursively defined structures CS 3090: Safety Critical Programming in C6  When two structures refer to each other, one must be declared in incomplete (prototype) fashion struct HUMAN; struct PET { char name[NAME_LIMIT]; char species[NAME_LIMIT]; struct HUMAN *owner; } fido = { ″ Fido ″, ″ Canis lupus familiaris ″ }; struct HUMAN { char name[NAME_LIMIT]; struct PET pets[PET_LIMIT]; } sam = { ″ Sam ″, {fido}}; We can’t initialize the owner member at this point, since it hasn’t been declared yet

 Direct access operator s.m  subscript and dot operators have same precedence and associate left-to-right, so we don’t need parentheses for sam.pets[0].species  Indirect access s->m : equivalent to (*s).m  Dereference a pointer to a structure, then return a member of that structure  Dot operator has higher precedence than indirection operator, so parentheses are needed in (*s).m (*fido.owner).name or fido.owner->name Member access CS 3090: Safety Critical Programming in C7. evaluated first: access owner member * evaluated next: dereference pointer to HUMAN. and -> have equal precedence and associate left-to-right

struct COST { int amount; char currency_type[2]; } struct PART { char id[2]; struct COST cost; int num_avail; } layout of struct PART : Here, the system uses 4-byte alignment of integers, so amount and num_avail must be aligned Four bytes wasted for each structure! Memory layout CS 3090: Safety Critical Programming in C8 idamountnum_avail cost currency_type

A better alternative (from a space perspective): struct COST { int amount; char currency_type; } struct PART { struct COST cost; char id[2]; int num_avail; } Memory layout CS 3090: Safety Critical Programming in C9 id amount num_avail cost currency_type

Bit fields CS 3090: Safety Critical Programming in C10  If space is a serious concern, you can select the number of bits used for each member struct CHAR { unsigned ch: 7; unsigned font: 6; unsigned size: 19; }; Layout possibilities (machine-dependent): chfontsize ch fontsize Note: This won’t work on machines with 16-bit int s Bit field members must be int s

Bit fields CS 3090: Safety Critical Programming in C11  Portability is an issue:  Do any bit field sizes exceed the machine’s int size?  Is there any pointer manipulation in your code that assumes a particular layout?  Bit fields are “syntactic sugar” for more complex shifting/masking  e.g. to get font value, mask off the ch and size bits, then shift right by 19  This is what actually happens in the object code – bit fields just make it look simpler at the source level

Structures as function arguments CS 3090: Safety Critical Programming in C12  Structures are scalars, so they can be returned and passed as arguments – just like int s, char s struct BIG changestruct(struct BIG s);  Call by value: temporary copy of structure is created  Caution: passing large structures is inefficient – involves a lot of copying  avoid by passing a pointer to the structure instead: void changestruct(struct BIG *s);  What if the struct argument is read-only?  Safe approach: use const void changestruct(struct BIG const *s);

Unions CS 3090: Safety Critical Programming in C13  Like structures, but every member occupies the same region of memory!  Structures: members are “and”ed together: “name and species and owner”  Unions: members are “xor”ed together union VALUE { float f; int i; char *s; }; /* either a float xor an int xor a string */

Unions CS 3090: Safety Critical Programming in C14  Up to programmer to determine how to interpret a union (i.e. which member to access)  Often used in conjunction with a “type” variable that indicates how to interpret the union value enum TYPE { INT, FLOAT, STRING }; struct VARIABLE { enum TYPE type; union VALUE value; }; Access type to determine how to interpret value

Unions CS 3090: Safety Critical Programming in C15  Storage  size of union is the size of its largest member  avoid unions with widely varying member sizes; for the larger data types, consider using pointers instead  Initialization  Union may only be initialized to a value appropriate for the type of its first member