Programming in C Structs and Unions. No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because.

Slides:



Advertisements
Similar presentations
2007 Pearson Education, Inc. All rights reserved C Structures, Unions, Bit Manipulations and Enumerations.
Advertisements

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Structures –Collections of related.
Chapter 10 C Structures, Unions, Bit Manipulations and Enumerations Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc.
Chapter 10 C Structures, Unions, Bit Manipulations, and Enumerations.
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.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Structures Functions and Arrays Dale Roberts, Lecturer Computer.
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.
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.
Enumerated data type & typedef. Enumerated Data Type An enumeration consists of a set of named integer constants. An enumeration type declaration gives.
ENUMERATED, typedef. ENUMERATED DATA TYPES An enumeration consists of a set of named integer constants. An enumeration type declaration gives the name.
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.
 2000 Prentice Hall, Inc. All rights reserved. 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. 1 Chapter 10 - C Structures, Unions, Bit Manipulations,
C and Data Structures Baojian Hua
 2000 Prentice Hall, Inc. All rights reserved. Chapter 10 - Structures, Unions, Bit Manipulations, and Enumerations Outline 10.1Introduction 10.2Structure.
Multidimensional Arrays C++ also allows an array to have more than one dimension. For example, a two-dimensional array consists of a certain number of.
Working with Structures. Structure Declaration ä Creates a user-defined data type. ä Gives the compiler a “head’s up” as to what the structure contains.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
C Tokens Identifiers Keywords Constants Operators Special symbols.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Cosc237/structures1 Structures aggregate data types record - single variable name for the whole collection composed of several variables - fields,BUT,
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.
9. Types Intro Programming in C++ Computer Science Dept Va Tech August, 2002 © Barnette ND & McQuain WD 1 Data Types data type:a collection of.
Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR.
User Defined Data Types - updated Chapter 10: User Defined Data Types Objectives: In this chapter you will learn about, Introduction Declaring.
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:
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.
Array, Structure and Union
 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)
1 C Language Structures. 2 Topics Concept of a structure Concept of a structure Structures in c Structures in c Structure declaration Structure declaration.
Programming in C Chars, Strings and Structs. ASCII The American Standard Code for Information Interchange (ASCII) character set, has 128 characters designed.
1 Structs. 2 Defining a Structure Often need to keep track of several pieces of information about a given thing. Example: Box We know its length width.
Chapter 10 Structures, Unions, Bit Manipulations, and Enumerations Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function.
1 EPSII 59:006 Spring HW’s and Solutions on WebCT.
C++ for Java Programmers Chapter 2. Fundamental Daty Types Timothy Budd.
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.
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.
CSE 251 Dr. Charles B. Owen Programming in C1 structs Aggregating associated data into a single variable Box width length height Circle radius int main()
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.
Functions Dr. Sajib Datta Functions A function is a self-contained unit of program code designed to accomplish a particular task. Some functions.
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 *
Java Programming Language Lecture27- An Introduction.
Structures, Unions, Enumerations
Chapter 10-1: Structure.
Structure, Unions, typedef and enumeration
C Structures, Unions, Bit Manipulations and Enumerations
C Programming Tutorial – Part I
C Structures, Unions, Bit Manipulations and Enumerations
Java Review: Reference Types
DATA HANDLING.
C Structures, Unions, and Enumerations
Programming in C #4 Structs and Unions.
Programming in C Structs and Unions.
C Structures, Unions, Bit Manipulations and Enumerations
Roadmap C: Java: Assembly language: OS: Machine code: Computer system:
Derived types.
CMSC 202 Classes and Objects.
C Structures, Unions, Bit Manipulations and Enumerations
QUIZ.
CS 240 – Lecture 7 Boolean Operations, Increment and Decrement Operators, Constant Types, enum Types, Precedence.
Structures, Unions, and Enumerations
Presentation transcript:

Programming in C Structs and Unions

No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because C is not an OOP language, there is no way to combine data and code into a single entity. C does allow us to combine related data into a structure using the keyword.C does allow us to combine related data into a structure using the keyword struct. All data in a variable can be accessed by any code.All data in a struct variable can be accessed by any code. Think of a as an OOP class in which all data members are public, and which has no methods.Think of a struct as an OOP class in which all data members are public, and which has no methods.

Struct definition The general form of a structure definition isThe general form of a structure definition is struct tag { member1_declaration; member2_declaration; member3_declaration;... memberN_declaration; }; where is the keyword, names this kind of, and are variable declarations which define the members. where struct is the keyword, tag names this kind of struct, and member_declarations are variable declarations which define the members. Note the semi-colon

C struct Example Defining a to represent a point in a coordinate planeDefining a struct to represent a point in a coordinate plane struct point { int x;/* x-coordinate */ int y;/* y-coordinate */ }; Given the declarationsGiven the declarations struct point p1; struct point p2; we can access the members of these variables: we can access the members of these struct variables: * the x-coordinate of p1 is * the y-coordinate of p1 is * the x-coordinate of p2 is * the y-coordinate of p2 is point is the struct tag p1.x p1.y p2.x p2.y

Using structs and members Like other variable types, variables (e.g. p1, p2) can be passed to functions as parameters and returned from functions as return types.Like other variable types, struct variables (e.g. p1, p2) can be passed to functions as parameters and returned from functions as return types. The members of a are variables just like any other and ca be used wherever any other variable of the same type may be used. For example, the members of the can then be used just like any other integer variables.The members of a struct are variables just like any other and ca be used wherever any other variable of the same type may be used. For example, the members of the struct point can then be used just like any other integer variables.

printPoint.c // struct point is a function parameter void printPoint( struct point aPoint ) { printf (“( %2d, %2d )”, aPoint.x, aPoint.y); } // struct point is the return type struct point inputPoint( ) { struct point inPoint; printf(“please input the x- and y-coordinates: “); scanf(“%d %d”, &inPoint.x, &inPoint.y); return inPoint; } int main ( ) { struct point endpoint; // endpoint is a struct point variable endpoint = inputPoint( ); // struct assignment.... more later printPoint( endpoint ); return 0; }

Initializing A struct A variable may be initialized when it is declared by providing the initial values for each member in the order they appearA struct variable may be initialized when it is declared by providing the initial values for each member in the order they appear struct point middle = { 6, -3 }; defines the variable named and initializes and defines the struct point variable named middle and initializes middle.x = 6 and middle.y = -3

struct Variants variables may be declared at the same time the struct is definedstruct variables may be declared at the same time the struct is defined struct point { int x, y; } endpoint, upperLeft; defines the structure named point AND declares the variables endpoint and upperLeft to be of this type.

struct typedef It’s common to use a for the name of a to make code more concise.It’s common to use a typedef for the name of a struct to make code more concise. typedef struct point { int x, y; } POINT; defines the structure named point and defines POINT as a typedef (alias) for the struct. We can now declare variables, parameters, etc., as struct point endpoint; or as POINT upperRight;

struct assignment The contents of a variable may be copied to another variable of the same type using the assignment (=) operatorThe contents of a struct variable may be copied to another struct variable of the same type using the assignment (=) operator After this code is executedAfter this code is executed struct point p1; struct point p2; p1.x = 42; p1.y = 59; p2 = p1;/* structure assignment copies members */ The values of ’s members are the same as ’s members. The values of p2 ’s members are the same as p1 ’s members. E.g. and E.g. p1.x = p2.x = 42 and p1.y = p2.y = 59

struct within a struct A data element in a may be another (similar to composition with classes in Java / C++).A data element in a struct may be another struct (similar to composition with classes in Java / C++). This example defines a line in the coordinate plane by specifying its endpoints as POINTThis example defines a line in the coordinate plane by specifying its endpoints as POINT structs typedef struct line { POINT leftEndPoint; POINT rightEndPoint; } LINE; Given the declarations below, how do we access the x- and y-coodinates of each line’s endpoints?Given the declarations below, how do we access the x- and y-coodinates of each line’s endpoints? struct line line1, line2; line1.leftEndPoint.xline1.rightEndPoint.y line2.leftEndPoint.xline2.rightEndPoint.y

1/20/1012 Arrays of struct Since a is a variable type, we can create arrays of just like we create arrays of primitives.Since a struct is a variable type, we can create arrays of structs just like we create arrays of primitives. Write the declaration for an array of 5 line structures name “lines”Write the declaration for an array of 5 line structures name “lines” struct line lines[ 5 ];or LINE lines[ 5 ]; Write the code to print the x-coordinate of the left end point of the 3rd line in the arrayWrite the code to print the x-coordinate of the left end point of the 3rd line in the array printf( “%d\n”, lines[2].leftEndPoint.x);

13 Array of struct Code /* assume same point and line struct definitions */ int main( ) { LINE sides[5]; int k; /* write code to initialize all data members to zero */ for (k = 0; k < 5; k++) { sides[k].leftEndPoint.x = 0; sides[k].leftEndPoint.y = 0; sides[k].rightEndPoint.x = 0; sides[k].rightEndPoint.y = 0; } /* call the printPoint( ) function to print ** the left end point of the 3 rd line */ printPoint( sides[2].leftEndPoint); return 0; }

Arrays within a struct Structs may contain arrays as well as primitive typesStructs may contain arrays as well as primitive types struct month { int nrDays; char name[ ]; }; struct month january = { 31, “JAN”};

A bit more complex struct month allMonths[ 12 ] = { {31, “JAN”}, {28, “FEB”}, {31, “MAR”}, {30, “APR”}, {31, “MAY”}, {30, “JUN”}, {31, “JUL”}, {31, “AUG”}, {30, “SEP”}, {31, “OCT”}, {30, “NOV”}, {31, “DEC”} }; // write the code to print the data for September printf( “%s has %d days\n”, allMonths[8].name, allMonths[8].nrDays); // what is the value of allMonths[3].name[1] P

Bitfields When saving space in memory or a communications message is of paramount importance, we sometimes need to pack lots of information into a small space. We can use syntax to define “variables” which are as small as 1 bit in size. These variables are known as “”.When saving space in memory or a communications message is of paramount importance, we sometimes need to pack lots of information into a small space. We can use struct syntax to define “variables” which are as small as 1 bit in size. These variables are known as “ bit fields ”. struct weather { unsigned int temperature : 5; unsigned int windSpeed : 6; unsigned int isRaining : 1; unsigned int isSunny : 1; unsigned int isSnowing : 1; };

Using Bitfields Bit fields are referenced like any other struct memberBit fields are referenced like any other struct member struct weather todaysWeather; todaysWeather.temperature = 44; todaysWeather.isSnowing = 0; todaysWeather.windSpeed = 23; /* etc */ if (todaysWeather.isRaining) printf( “%s\n”, “Take your umbrella”); if (todaysWeather.temperature < 32 ) printf( “%s\n”, “Stay home”);

More on Bit fields Almost everything about bit fields is implementation (machine and compiler) specific.Almost everything about bit fields is implementation (machine and compiler) specific. Bit fields may only defined asBit fields may only defined as (unsigned) ints Bit fields do not have addresses, so the operator cannot be applied to themBit fields do not have addresses, so the & operator cannot be applied to them We’ll see more on this laterWe’ll see more on this later

Unions A is a variable type that may hold different type of members of different sizes, BUT only one type at a time.. The compiler assigns enough memory for the largest of the member types.A union is a variable type that may hold different type of members of different sizes, BUT only one type at a time. All members of the union share the same memory. The compiler assigns enough memory for the largest of the member types. The syntax for defining a and using its members is the same as the syntax for a.The syntax for defining a union and using its members is the same as the syntax for a struct.

Formal Union Definition The general form of a union definition isThe general form of a union definition is union tag { member1_declaration; member2_declaration; member3_declaration;... memberN_declaration; }; where is the keyword, tag names this kind of, and m are variable declarations which define the members. Note that the syntax for defining a is exactly the same as the syntax for a. where union is the keyword, tag names this kind of union, and m ember_declarations are variable declarations which define the members. Note that the syntax for defining a union is exactly the same as the syntax for a struct.

An application of Unions struct square { int length; }; struct circle { int radius; }; struct rectangle { int width; int height; }; enum shapeType {SQUARE, CIRCLE, RECTANGLE }; union shapes { struct square aSquare; struct circle aCircle; struct rectangle aRectangle; }; struct shape { enum shapeType type; union shapes theShape; };

An application of Unions (2) double area( struct shape s) { switch( s.type ) { case SQUARE: return s.theShape.aSquare.length * s.theShape.aSquare.length; case CIRCLE: return 3.14 * s.theShape.aCircle.radius * s.theShape.aCircle.radius; case RECTANGLE : return s.theShape.aRectangle.height * s.theShape.aRectangle.width; }

Union vs. Struct SimilaritiesSimilarities –Definition syntax virtually identical –Member access syntax identical DifferencesDifferences –Members of a struct each have their own address in memory. –The size of a struct is at least as big as the sum of the sizes of the members (more on this later) –Members of a union share the same memory. – The size of a union is the size of the largest member.