Structures and Unions in C Alan L. Cox

Slides:



Advertisements
Similar presentations
CS 11 C track: lecture 7 Last week: structs, typedef, linked lists This week: hash tables more on the C preprocessor extern const.
Advertisements

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.
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.
Copyright © 2000, Daniel W. Lewis. All Rights Reserved. CHAPTER 3 GETTING THE MOST OUT OF C.
The Preprocessor Underlying C Language Features Copyright © 2012 by Yong-Gu Lee
CS1061: C Programming Lecture 21: Dynamic Memory Allocation and Variations on struct A. O’Riordan, 2004, 2007 updated.
Arrays in CCS-2301, B-Term Arrays in C (including a brief introduction to pointers) CS-2301, System Programming for Non-Majors (Slides include materials.
C Programming Basics Lecture 5 Engineering H192 Winter 2005 Lecture 05
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
Lecture 3 1. Structures 2. Abstract Data Types. STRUCTURES WHY ARE STRUCTURES NEEDED? If the predefined types are not adequate to model the object, create.
C structures and unions (Reek, Ch. 10) 1CS 3090: Safety Critical Programming in C.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
CS1061 C Programming Lecture 4: Indentifiers and Integers A.O’Riordan, 2004.
Guide To UNIX Using Linux Third Edition
Data Types.
Arrays and Pointers in C Alan L. Cox
Lecture 8. Lecture 8: Outline Structures [Kochan, chap 9] –Defining and using Structures –Functions and Structures –Initializing Structures. Compound.
Engineering Computing I Chapter 6 Structures. Sgtructures  A structure is a collection of one or more variables, possibly of different types, grouped.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
C Tokens Identifiers Keywords Constants Operators Special symbols.
Lecturer: Omid Jafarinezhad Sharif University of Technology Department of Computer Engineering 1 Fundamental of Programming (C) Lecture 8 Structures, Unions,
C# D1 CSC 298 Elements of C# code (part 2). C# D2 Writing a class (or a struct)  Similarly to Java or C++  Fields: to hold the class data  Methods:
Programming in C Structs and Unions. Java vs C Suppose you were assigned a write an application about points and straight lines in a coordinate plane.
Lecture Contents Arrays and Vectors: Concepts of pointers and references. Pointer declarations and initialization. Pointer Operators. Dynamic Memory Allocation.
Dennis Ritchie 1972 AT & T Bell laboratories (American Telephone and Telegraph) USA 1www.gowreeswar.com.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 5P. 1Winter Quarter C Programming Basics.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
1 Homework HW5 due today Review a lot of things about allocation of storage that may not have been clear when we covered them in our initial pass Introduction.
 2007 Pearson Education, Inc. All rights reserved C Structures, Unions, Bit Manipulations and Enumerations.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Arrays in CCIS 1057 Fall Arrays in C (with a brief Introduction to Pointers) CIS 1057 Computer Programming in C Fall 2013 (Slides include materials.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Today’s Material Aggregate Data Types: Structures and Unions
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 5P. 1Winter Quarter C Programming Basics Lecture 5.
Senem Kumova Metin STRUCTURES continues CHAPTER 9 in A Book in C.
CS 261 – Data Structures Introduction to C Programming.
CS 261 – Data Structures C Pointers Review. C is Pass By Value Pass-by-value: a copy of the argument is passed in to a parameter void foo (int a) { a.
Chapter 10 Structures, Unions, Bit Manipulations, and Enumerations Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering.
Memory Allocation Alan L. Cox Objectives Be able to recognize the differences between static and dynamic memory allocation Be able to use.
Functions, Scope, and The Free Store Functions Functions must be declared by a function prototype before they are invoked, return_type Function_name(type,
C++ for Java Programmers Chapter 2. Fundamental Daty Types Timothy Budd.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 12 – C: structs, linked lists, and casts.
Structures and Union. Review bitwise operations –you need them for performance in terms of space and time –shifts are equivalent to arithmetics enumeration.
Introduction to Computers and Programming Class 24 Structures (structs) Professor Avi Rosenfeld.
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Structure A collection of values (members) struct date{ int day; char month[10]; int year; }; Declare a structure variable struct date today; struct struct_name.
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.
CGS 3460 Thus Far n Whenever we declare a variable, we specified its data type. n The data type helped us identify the type of information that a variable.
Arrays What is an array… –A data structure that holds a set of homogenous elements (of the same type) –Associate a set of numbers with a single variable.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Advanced Programming Constants, Declarations, and Definitions Derived Data Types.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
Windows Programming Lecture 06. Data Types Classification Data types are classified in two categories that is, – those data types which stores decimal.
©2004 Joel Jones 1 CS 403: Programming Languages Lecture 3 Fall 2004 Department of Computer Science University of Alabama Joel Jones.
Java Programming Language Lecture27- An Introduction.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Lecture 10 union, enumeration, bit
C++ Lesson 1.
Data types Data types Basic types
Structures.
Structures and Unions in C
CSE 374 Programming Concepts & Tools
C Basics.
Lecture 13 Structs.
Structure.
C Structures, Unions, Bit Manipulations and Enumerations
C Structures, Unions, Bit Manipulations and Enumerations
2. Second Step for Learning C++ Programming • Data Type • Char • Float
C Language B. DHIVYA 17PCA140 II MCA.
Presentation transcript:

Structures and Unions in C Alan L. Cox

Cox / RixnerStructures and Unions2 Administrivia Assignment 1 is due tonight Textbook  Lectures begin covering material that is also covered by the textbook on 2/3  Assignment 3 (assigned 2/5) requires use of the textbook

Objectives Be able to use compound data structures in programs Be able to use compound data structures as function arguments either by value or by reference Be able to do simple bit-vector manipulations Cox / RixnerStructures and Unions3

Cox / RixnerStructures and Unions4 Structures Compound data: A date is  an int month and  an int day and  an int year Unlike Java, C doesn’t automatically define functions for initializing and printing … struct ADate { int month; int day; int year; }; struct ADate date; date.month = 1; date.day = 22; date.year = 2015;

Cox / RixnerStructures and Unions5 Structure Representation & Size sizeof(struct …) = sum of sizeof( field ) +alignment padding Processor- and compiler-specific 6261EFBEADDE c1c2i padding struct CharCharInt { char c1; char c2; int i; } foo; foo.c1 = ’a’; foo.c2 = ’b’; foo.i = 0xDEADBEEF; x86 uses “little-endian” representation

Cox / RixnerStructures and Unions6 Typedef Mechanism for creating new type names  New names are an alias for some other type  May improve clarity and/or portability of the program typedef long int64_t; typedef struct ADate { int month; int day; int year; } Date; int64_t i = ; Date d = {1, 22, 2015}; Overload existing type names for clarity and portability Simplify complex type names

Cox / RixnerStructures and Unions7 Constants Allow consistent use of the same constant throughout the program  Improves clarity of the program  Reduces likelihood of simple errors  Easier to update constants in the program int array[10]; for (i=0; i<10; i++) { … } #define SIZE 10 int array[SIZE]; for (i=0; i<SIZE; i++) { … } Preprocessor directive Constant names are capitalized by convention Define once, use throughout the program

Cox / RixnerStructures and Unions8 Arrays of Structures Date birthdays[NFRIENDS]; bool check_birthday(Date today) { int i; for (i = 0; i < NFRIENDS; i++) { if ((today.month == birthdays[i].month) && (today.day == birthdays[i].day)) return (true); return (false); } Constant Array declaration Array index, then structure field

Cox / RixnerStructures and Unions9 Pointers to Structures Date create_date1(int month, int day, int year) { Date d; d.month = month; d.day = day; d.year = year; return (d); } void create_date2(Date *d, int month, int day, int year) { d->month = month; d->day = day; d->year = year; } Copies date Pass-by-reference Date today; today = create_date1(1, 22, 2015); create_date2(&today, 1, 22, 2015);

Cox / RixnerStructures and Unions10 Pointers to Structures (cont.) void create_date2(Date *d, int month, int day, int year) { d->month = month; d->day = day; d->year = year; } void fun_with_dates(void) { Date today; create_date2(&today, 1, 22, 2015); } today.month: today.day: today.year: 0x1000 0x1004 0x1008 month: 1 day: 22 year: x30A0 0x30A4 0x30A8 d: 0x1000 0x

Cox / RixnerStructures and Unions11 Pointers to Structures (cont.) Date * create_date3(int month, int day, int year) { Date *d; d->month = month; d->day = day; d->year = year; return (d); } What is d pointing to?!?! (more on this later)

CoxStructures and Unions12 Abstraction in C struct widget; struct widget *widget_create(void); int widget_op(struct widget *widget, int operand); void widget_destory(struct widget *widget); From the #include file widget.h: From the file widget.c: #include “widget.h” struct widget { int x; … }; Definition is hidden! Cox / RixnerStructures and Unions12

Cox / RixnerStructures and Unions13 Collections of Bools (Bit Vectors) Byte, word,... can represent many booleans One per bit, e.g., = false, false, true,..., true Bit-wise operations: Bit-wise AND: & == Bit-wise OR: | == Bit-wise NOT: ~ == Bit-wise XOR: ^ ==

Cox / RixnerStructures and Unions14 Operations on Bit Vectors const unsigned int low_three_bits_mask = 0x7; unsigned int bit_vec = 0x15; 0… … Always use C’s unsigned types for bit vectors A mask indicates which bit positions we are interested in 0… == 0… & 0… important_bits = bit_vec & low_three_bits_mask; Selecting bits: Result = ?

Cox / RixnerStructures and Unions15 Operations on Bit Vectors const unsigned int low_three_bits_mask = 0x7; unsigned int bit_vec = 0x15; 0… … bit_vec |= low_three_bits_mask; Setting bits: Result = ? 0… == 0… | 0…

Cox / RixnerStructures and Unions16 Operations on Bit Vectors const unsigned int low_three_bits_mask = 0x7; unsigned int bit_vec = 0x15; 0… … bit_vec &= ~low_three_bits_mask; Clearing bits: Result = ? 0… == 0… & ~0…

Cox / RixnerStructures and Unions17 Bit-field Structures Special syntax packs structure values more tightly Similar to bit vectors, but arguably easier to read  Nonetheless, bit vectors are more commonly used. Padded to be an integral number of words  Placement is compiler- specific …… f1f2f3 struct Flags { int f1:3; unsigned int f2:1; unsigned int f3:2; } my_flags; my_flags.f1 = -2; my_flags.f2 = 1; my_flags.f3 = 2;

Cox / RixnerStructures and Unions18 Unions Choices: An element is  an int i or  a char c sizeof(union …) = maximum of sizeof( field ) EFBEADDE c i padding union AnElt { int i; char c; } elt1, elt2; elt1.i = 4; elt2.c = ’a’; elt2.i = 0xDEADBEEF;

Cox / RixnerStructures and Unions19 Unions A union value doesn’t “know” which case it contains union AnElt { int i; char c; } elt1, elt2; elt1.i = 4; elt2.c = ’a’; elt2.i = 0xDEADBEEF; if (elt1 currently has a char) … How should your program keep track whether elt1, elt2 hold an int or a char ? ? ? Basic answer: Another variable holds that info

Cox / RixnerStructures and Unions20 Tagged Unions Tag every value with its case I.e., pair the type info together with the union Implicit in Java, Scheme, ML, … Enum must be external to struct, so constants are globally visible. Struct field must be named. enum Union_Tag {IS_INT, IS_CHAR}; struct TaggedUnion { enum Union_Tag tag; union { int i; char c; } data; };

Cox / RixnerStructures and Unions21 Next Time Memory Allocation