Structures, Unions, and Typedefs

Similar documents
Structures. 5 th March Spring 2012 Programming and Data Structure 1

Linked Lists in C and C++

Dynamic Memory Allocation (and Multi-Dimensional Arrays)

Arrays and Pointers in C & C++

Binary Trees (and Big O notation)

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Accessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Programming Assignment #4 Binary Trees in C++

Classes, Constructors, etc., in C++

Strings in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Your first C and C++ programs

Derived Classes in C++

Data Representation and Storage

Containers and the Standard Template Library (STL)

CS240: Programming in C

Iterators. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Structures. Today s Goals. Structure Operations. Structure Type Declaration. Struct Instance. typedef. CS246 Lec12. Structures

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

Data Representation and Storage. Some definitions (in C)

Writing Functions in C

Programming in C. 3. Pointers and Structures. Dr. Neel Krishnaswami University of Cambridge

CS3157: Advanced Programming. Announcement

C LANGUAGE AND ITS DIFFERENT TYPES OF FUNCTIONS

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

Introduction to C++ with content from

Computer System and programming in C

Systems Programming. 05. Structures & Trees. Alexander Holupirek

TDDB68 Concurrent Programming and Operating Systems. Lecture 2: Introduction to C programming

Declaration Syntax. Declarations. Declarators. Declaration Specifiers. Declaration Examples. Declaration Examples. Declarators include:

High Performance Computing in C and C++

CS Programming In C

C Programming Language: C ADTs, 2d Dynamic Allocation. Math 230 Assembly Language Programming (Computer Organization) Thursday Jan 31, 2008

Exception Handling in C++

QUIZ. What is wrong with this code that uses default arguments?

A Deeper Look at Classes

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

C Language, Token, Keywords, Constant, variable

Computer Systems Principles. C Pointers

CS429: Computer Organization and Architecture

Variables in C. Variables in C. What Are Variables in C? CMSC 104, Fall 2012 John Y. Park

Templates (again) Professor Hugh C. Lauer CS-2303, System Programming Concepts

Fast Introduction to Object Oriented Programming and C++

PPP Style Guide Stroustrup 1/29/2010. PPP Style Guide. Bjarne Stroustrup

CSE 230 Intermediate Programming in C and C++

Short Notes of CS201

Structures and Pointers

Fundamental Concepts and Definitions

12 CREATING NEW TYPES

CS201 - Introduction to Programming Glossary By

Two s Complement Review. Two s Complement Review. Agenda. Agenda 6/21/2011

Kurt Schmidt. October 30, 2018

CS349/SE382 A1 C Programming Tutorial

Unit IV & V Previous Papers 1 mark Answers

6.096 Introduction to C++ January (IAP) 2009

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory

Data Types. Every program uses data, either explicitly or implicitly to arrive at a result.

CSE 220: Systems Programming

CS240: Programming in C

Structures, Unions Alignment, Padding, Bit Fields Access, Initialization Compound Literals Opaque Structures Summary. Structures

G52CPP C++ Programming Lecture 8. Dr Jason Atkin

EL6483: Brief Overview of C Programming Language

CS558 Programming Languages Winter 2018 Lecture 4a. Andrew Tolmach Portland State University

Motivation was to facilitate development of systems software, especially OS development.

C-types: basic & constructed. C basic types: int, char, float, C constructed types: pointer, array, struct

Variables in C. CMSC 104, Spring 2014 Christopher S. Marron. (thanks to John Park for slides) Tuesday, February 18, 14

Vector and Free Store (Vectors and Arrays)

A student was asked to point out interface elements in this code: Answer: cout. What is wrong?

CS201 - Lecture 1 The C Programming Language

COMP26120: Linked List in C (2018/19) Lucas Cordeiro

CS 110 Computer Architecture. Lecture 2: Introduction to C, Part I. Instructor: Sören Schwertfeger.

CS558 Programming Languages

Roadmap. Java: Assembly language: OS: Machine code: Computer system:

Algorithms, Data Structures, and Problem Solving

C Programming Review CSC 4320/6320

FUNCTION POINTERS. int (*pf)(); // pf is a pointer to a function returning an int.

Never give in, never give in, never give in in nothing great or small, large or petty never give in except to convictions of honor and good sense

Intro to C: Pointers and Arrays

Learning Objectives. Introduction to Arrays. Arrays in Functions. Programming with Arrays. Multidimensional Arrays

Types and Structures

EL2310 Scientific Programming

Object Reference and Memory Allocation. Questions:

Presented By : Gaurav Juneja

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

CSE351 Spring 2010 Final Exam (9 June 2010)

C Structures & Dynamic Memory Management

CS 261 Fall Mike Lam, Professor. Structs and I/O

Chapter 1 & 2 Introduction to C Language

The C Programming Language

C Programming. Course Outline. C Programming. Code: MBD101. Duration: 10 Hours. Prerequisites:

Binghamton University. CS-120 Summer Introduction to C. Text: Introduction to Computer Systems : Chapters 11, 12, 14, 13

CSE351 Spring 2010 Final Exam (9 June 2010)

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Allocating Space

CSCI 2212: Intermediate Programming / C Storage Class and Dynamic Allocation

QUIZ. What are 3 differences between C and C++ const variables?

CS561 Manju Muralidharan Priya Structures in C CS200 STRUCTURES. Manju Muralidharan Priya

High Performance Computing MPI and C-Language Seminars 2009

Tokens, Expressions and Control Structures

Fundamentals of Programming. Lecture 12: C Structures, Unions, Bit Manipulations and Enumerations

Transcription:

Structures, Unions, and Typedefs Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter Savitch, The C++ Programming Language, Special Edition, by Bjarne Stroustrup, and from C: How to Program, 5 th and 6 th editions, by Deitel and Deitel) 1

Reading Assignment Chapter 6 of Kernighan & Ritchie 2

Structures and Unions The last major language facility in C to be introduced in this course. Essential for building up interesting data structures e.g., Data structures of multiple values of different kinds Data structures of indeterminate size 3

Definition Structure A collection of one or more variables, typically of different types, grouped together under a single name for convenient handling Known as struct in C and C++ 4

struct Defines a new data type E.g., I.e., a new kind of data entity that compiler regards as a unit struct motor { float volts; //voltage of the motor float amps; //amperage of the motor int phases; //# of phases of the motor float rpm; //rotational speed of motor }; //struct motor 5

struct Defines a new type E.g., struct motor { float volts; float amps; int phases; float rpm; }; //struct motor Note: name of type is optional if you are just declaring a single struct (middle p. 128 of K&R) 6

struct Defines a new type E.g., struct motor { float volts; float amps; int phases; float rpm; }; //struct motor Members of the struct A member of a struct is analogous to a field of a class in Java 7

Declaring struct variables struct motor p, q, r; Declares and sets aside storage for three variables p, q, and r each of type struct motor struct motor M[25]; Declares a 25-element array of struct motor; allocates 25 units of storage, each big enough to hold the data of one struct motor struct motor *m; Declares a pointer to an object of type struct motor 8

Accessing Members of a struct Let struct motor p; struct motor q[10]; Then p.volts p.amps p.phases p.rpm is the voltage is the amperage is the number of phases is the rotational speed Like Java! q[i].volts q[i].rpm is the voltage of the ith motor is the speed of the ith motor 9

Accessing Members of a struct (continued) Let struct motor *p; Then (*p).volts (*p).phases is the voltage of the motor pointed to by p is the number of phases of the motor pointed to by p 10

Accessing Members of a struct (continued) Let struct motor *p; Then (*p).volts (*p).phases is the voltage of the motor pointed to by p is the number of phases of the motor pointed to by p 11

Accessing Members of a struct (continued) Let struct motor *p; Then (*p).volts (*p).phases is the voltage of the motor pointed to by p is the number of phases of the motor pointed to by p Reason: you really want expression m.volts * m.amps to mean what you think it should mean! 12

Accessing Members of a struct (continued) The (*p).member notation is a nuisance Clumsy to type; need to match ( ) Too many keystrokes This construct is so widely used that a special notation was invented, i.e., p->member, where p is a pointer to the structure Ubiquitous in C and C++ 13

Previous Example Becomes Let struct motor *p; Then p -> volts p -> phases is the voltage of the motor pointed to by p is the number of phases of the motor pointed to by p 14

Operations on struct Copy/assign struct motor p, q; p = q; Get address struct motor p; struct motor *s s = &p; Access members p.volts; s -> amps; 15

Operations on struct (continued) Remember: Passing an argument by value is an instance of copying or assignment Passing a return value from a function to the caller is an instance of copying or assignment E.g.: struct motor f(struct motor g) { struct motor h = g;...; return h; } 16

Assigning to a struct K & R say (p. 131) If a large structure is to be passed to a function, it is generally more efficient to pass a pointer than to copy the whole structure I disagree: Copying is very fast on modern computers Creating an object with malloc() and assigning a pointer is not as fast Esp. if you want the object passed or returned by value In real life situations, it is a judgment call 17

Initialization of a struct Let struct motor { float volts; float amps; int phases; float rpm; }; //struct motor Then struct motor m = {208, 20, 3, 1800}; initializes the struct See also p. 133 of K&R for initializing arrays of structs 18

Why structs? Open-ended data structures E.g., structures that may grow during processing Avoids the need for realloc() and a lot of copying Self-referential data structures Lists, trees, etc. 19

Example struct item { char *s; int len; struct item *next; } I.e., an item can point to another item which can point to another item which can point to yet another item etc. Thereby forming a list of items Called a Linked List 20

A note about structs and pointers The following is legal: /* in a.c or.h file */ struct item; struct item *p, *q; /* In another file */ struct item { int member1; float member2; struct item *member3; // other members }; Called an opaque type! Program can use pointers to items but cannot see into items. Cannot define any items, cannot malloc() any items, etc. Implementer of item can change the definition without forcing users of pointers to change their code! 21

Another note about structs The following is not legal: struct motor { float volts; float amps; float rpm; unsigned int phases; }; //struct motor motor m; motor *p; You must write struct motor m; struct motor *p; 22

Typedef Definition: a typedef is a way of renaming a type See 6.7 E.g., typedef struct motor Motor; Motor m, n; Motor *p, r[25]; Motor function(const Motor m; ); 23

typedef (continued) typedef may be used to rename any type Convenience in naming Clarifies purpose of the type Cleaner, more readable code Portability across platforms E.g., typedef char *String; E.g., typedef int size_t; typedef long int32; typedef long long int64; 24

typedef (continued) typedef may be used to rename any type Convenience in naming Clarifies purpose of the type Cleaner, more readable code Portability across platforms E.g., typedef char *String; E.g., typedef int size_t; typedef long int32; typedef long long int64; 25

Revisit note about structs and pointers The following is legal: /* in a.h file */ typedef struct _item Item; Item *p, *q; /* In another file */ struct _item { char *info; Item *nextitem; }; I.e., allows programmer to leave out word struct and hide details of struct 26

Questions about structs and pointers? 27

Unions A union is like a struct, but only one of its members is stored, not all I.e., a single union variable may hold different types at different times Storage is large enough to hold largest member Members are overlaid on top of each other E.g., union { int float char } u; ival; fval; *sval; 28

Unions (continued) It is programmer s responsibility to keep track of which type is stored in a union at any given time! E.g., (p. 148) struct taggeditem { enum {itype, ftype, ctype} tag; union { int ival; float fval; char *sval; } u; }; 29

Unions (continued) It is programmer s responsibility to keep track of which type is stored in a union at any given time! E.g., (p. 148) struct taggeditem { enum {itype, ftype, ctype} tag; }; union { int float char } u; ival; fval; *sval; Members of struct are: enum tag; union u; Value of tag says which member of u to use 30

Unions (continued) unions are used much less frequently than structs mostly in the inner details of operating system in device drivers in embedded systems where you have to access registers defined by the hardware May be useful in PA #3 But not required 31

Questions? 32