Today’s Material Aggregate Data Types: Structures and Unions

Slides:



Advertisements
Similar presentations
EASTERN MEDITERRANEAN UNIVERSITY EENG212 ALGORITHMS & DATA STRUCTURES Structures in C.
Advertisements

Chapter 10 C Structures, Unions, Bit Manipulations and Enumerations Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc.
Programming in C Chapter 10 Structures and Unions
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.
1 Structures. 2 User-Defined Types C provides facilities to define one’s own types. These may be a composite of basic types ( int, double, etc) and other.
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”)
Structure.
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.
Run-time organization  Data representation  Storage organization: –stack –heap –garbage collection Programming Languages 3 © 2012 David A Watt,
Kernighan/Ritchie: Kelley/Pohl:
Structures. An array allows us to store a collection of variables However, the variables must be of the same type to be stored in an array E.g. if we.
C and Data Structures Baojian Hua
C structures and unions (Reek, Ch. 10) 1CS 3090: Safety Critical Programming in C.
User-defined Structure Types Structures: collection of data of different types. We can define a structure type student_t : typedef struct { string name;
Pointers: Part I. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program.
Engineering Computing I Chapter 6 Structures. Sgtructures  A structure is a collection of one or more variables, possibly of different types, grouped.
DCT1063 Programming 2 CHAPTER 5 ADVANCED DATA TYPE (part 1) Mohd Nazri Bin Ibrahim Faculty of Computer Media and Technology TATi University College
Functions, Pointers, Structures Keerthi Nelaturu.
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,
1 Pointers and Arrays. 2 When an array is declared,  The compiler allocates sufficient amount of storage to contain all the elements of the array in.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 10 - C Structures, Unions, Bit Manipulations,
GUIDED BY- A.S.MODI MADE BY- 1. SHWETA ALWANI 2. PRIYANKA.
Learners Support Publications Classes and Objects.
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
Structured Programming Instructor: Prof. K. T. Tsang Lecture 11: Structure and Union 1.
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
16. STRUCTURES, UNIONS, AND ENUMERATIONS. Declaring Structures A structure is a collection of one or more components (members), which may be of different.
1 6.1 Basics of Structures 6.2 Structures and Functions 6.3 Arrays of Structures 6.4 Pointers to Structures 6.5 Self-referential Structures + Linked List.
Senem Kumova Metin STRUCTURES continues CHAPTER 9 in A Book in C.
 Structures are like arrays except that they allow many variables of different types grouped together under the same name. For example you can create.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 13: Data structures in C.
1 C Language Structures. 2 Topics Concept of a structure Concept of a structure Structures in c Structures in c Structure declaration Structure declaration.
Structures and Unions in C Alan L. Cox
+ Structures and Unions. + Introduction We have seen that arrays can be used to represent a group of data items that belong to the same type, such as.
Structured Programming Approach Module VIII - Additional C Data Types Structures Prof: Muhammed Salman Shamsi.
CPS120: Introduction to Computer Science Lecture 15A Structures.
Pointers *, &, array similarities, functions, sizeof.
Topics memory alignment and structures typedef for struct names bitwise & for viewing bits malloc and free (dynamic storage in C) new and delete (dynamic.
+ Pointers. + Content Address of operator (&) Pointers Pointers and array.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 12 – C: structs, linked lists, and casts.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 2 – August 23, 2001.
Pointers PART - 2. Pointers Pointers are variables that contain memory addresses as their values. A variable name directly references a value. A pointer.
Structures and Union. Review bitwise operations –you need them for performance in terms of space and time –shifts are equivalent to arithmetics enumeration.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI N305 Structures Declarations.
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 251 Dr. Charles B. Owen Programming in C1 structs Aggregating associated data into a single variable Box width length height Circle radius int main()
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.
CSC 107 – Programming For Science. Today’s Goal  Discover best uses of structures in a program  How we can mix pointers inside structures  Assigning.
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. INTRODUCTION A structure is same as that of records. It stores related information about an entity. Structure is basically a user defined.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Chapter 11 Structures, Unions and Typedef 11.1 Structures Structures allow us to group related data items of different types under a common name. The individual.
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)
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
Structures, Unions, Enumerations
DATA HANDLING.
Machine-Level Programming 6 Structured Data
Roadmap C: Java: Assembly language: OS: Machine code: Computer system:
Classes and Objects.
CSCE 206 Lab Structured Programming in C
User-defined data types
Chapter 11 Structure and Union Types.
Structures, Unions, and Enumerations
Structures Declarations CSCI 230
Presentation transcript:

Today’s Material Aggregate Data Types: Structures and Unions Motivation Definition and Declaration Representation Initialization Access Array of Structures Structures as function parameters Layout in Memory Unions

Motivation Data frequently occurs in groups For example a school has to keep track of some information for each of its students This information can be things such as Name Department Gpa Email address Courses takes & grades Address …

Motivation (cont) Accessing these values are simplified if they are stored together We cannot use an array to store these values together. Why? Because they are of different type C provides what is called a “structure” to store values with dissimilar types together Also known as a “record” A structure is a collection of values called members that can be of different types

Structure: Definition & Declaration A structure is a collection of values called members that can be of different types struct TAG {member list} variableList; /* TAG and variableList are optional */ /* No tag. Just declare * one variable */ struct { int i; char c; float f; } x; /* Give a name (tag) */ struct Simple { int i; char c; float f; }; /* declare a variable later */ struct Simple y;

typedef + Structures It is usually a good idea to define a new type using typedef instead of using “struct TAG” typedef struct Student { char name[40]; int dept; float gpa; char email[30]; } Student; /* Declare a variable */ struct Student s1; Student s2;

Structure Initialization Just like any other variable, you can initialize structure members during declaration Student s1={“Ali Veli”, 101, 3.10, “aliveli@anadolu.edu.tr”}; Student s2={“Veli Kasap”, 102, 2.10, “vkasap@anadolu.edu.tr”}; As with array initializers, an initializer can be shorter than the structure it is initializing Any leftover members are set to 0 typedef struct Simple { int i; char c; float f; } Simple; Simple z = {2}; /* c and f are set to 0 */

Accessing Structure Members (2) How to access structure members through a pointer? typedef struct Simple { int i; char c; float f; } Simple; Simple x; Simple *ps = &x; x.i = 4; (*ps).i = 4; (*ps).c = ‘A’; (*ps).f = 3.33; /* C provides an alternative * way to access the members * of a structure through a * pointer using -> operator */ ps->i = 4; ps->c = ‘A’; ps->f = 3.33;

Array of Structures It is possible to declare an array of structures Student students[2]; strcpy(students[0].name, “Veli Gocer”); students[0].dept = 101; students[0].gpa = 2.85; strcpy(students[0].email, “vgocer@anadolu.edu.tr”); /* It is possible to assign a structure to another */ students[1] = students[0]; /* Assignment copies the contents of structure * students[0] to the structure students[1]. * This is a memory-to-memory copy in its entirety */

Structures as Function Parameters As with all function arguments, structures are passed by value Thus any change made to a function parameter is not reflected to the function argument void F1(Simple s){ s.i = 2; s.c = ‘T’; s.f = 5.32; } /* end-F1 */ main(){ Simple x = {3, ‘A’, 4.35}; F1(x); printf(“x.i: %d, x.c: %c, x.f: .2f\n”, x.i, x.c, x.f); } /* end-main */ x.i: 3, x.c: A, x.f: 4.35

Structures as Function Parameters To change a structure argument inside a function, pass the structure’s address void F2(Simple *ps){ ps->i = 2; ps->c = ‘T’; ps->f = 5.32; } /* end-F2 */ main(){ Simple x = {3, ‘A’, 4.35}; F2(&x); printf(“x.i: %d, x.c: %c, x.f: .2f\n”, x.i, x.c, x.f); } /* end-main */ x.i: 2, x.c: T, x.f: 5.32

Returning Structures from Functions You can return a structure from a function This is very inefficient and not recommended Simple F3(Simple s){ s.i = 22; s.c = ‘Y’; s.f = 6.66; return s; } /* end-F3 */ Simple F4(int i, char c, float f){ Simple s; s.i = i; s.c = c; s.f = f; return s; } /* end-F4 */ main(){ Simple x = {3, ‘A’, 4.35}; x = F3(x); printf(“x.i: %d, x.c: %c, x.f: .2f\n”, x.i, x.c, x.f); x = F4(8, ‘Z’, 9.99); } /* end-main */ x.i: 22, x.c: Y, x.f: 6.66 x.i: 8, x.c: Z, x.f: 9.99

Complex Structure Declarations You can declare complex structures by nesting one structure inside another typedef struct { int i; char c; float f; } Simple; int a; Simple s; struct{ float b; }x; } Complex; Complex c; /* Access members of c */ c.a = 5; c.s.i = 3; c.s.c = ‘B’; c.s.f = 4.44; c.x.a = 2; c.x.b = 4.52; c.f = 3.45;

Layout of Structures in Memory(1) Structure members are stored consecutively in memory 100 Address unused 101 102 103 104 105 106 107 108 109 s.i 110 111 s.c s.f &s &s.i &s.c &s.f typedef struct{ int i; char c; float f; } Simple; Simple s; 3 bytes (105, 106, 107) are unused s.f starts at a 4-byte boundary due to alignment constraints

Layout of Structures in Memory(2) Member alignment plays a crutial role to determine the amount of space a structure will occupy in memory struct X { char c1; int i; char c2; }; struct Y { int i; char c1; char c2; }; sizeof(struct X) = 12 sizeof(struct Y) = 8 Not 6 because if we declare an array of structures, the next structure must start at a 4-byte boundary

Union: Definition A union is a structure that consists of one or members which may be of different types However, the compiler allocates only enough space for the largest of the members in a union Thus the members of a union overlay each other within this space Assigning a new value to one member alters the values of all the other members as well

Union: Declaration & Layout struct { int i; char c[4]; }s; union { int i; char c[4]; } u1; union { int i; float f; double d; } u2; 100 101 102 103 104 105 106 107 s.i s.c[0] s.c[1] s.c[2] s.c[3] sizeof(s) = 8 100 101 102 103 u1.i sizeof(u1) = 4 u1.c[1] u1.c[0] u1.c[2] u1.c[3] 100 101 102 103 104 105 106 107 u2.i sizeof(u2) = 8 u2.d u2.f

Union: Manipulation union { struct { union { int i; int i; int i; char c[4]; }s; union { int i; char c[4]; } u1; union { int i; float f; double d; } u2; /* set s.c only. s.i is not changed */ s.c[0]=1; s.c[1]=2; s.c[2]=3; s.c[4]=4; /* set s.c */ s.i = 0x12345678; /* changes s.i only. s.c is not changed */ printf(“%x-%x-%x-%x\n”, s.c[0], s.c[1], s.c[2], s.c[3]); /* Set u1.c. Changes u1.i as well */ u1.c[0]=1; u1.c[1]=2; u1.c[2]=3; u1.c[4]=4; u1.i = 0x12345678; /* Changes u1.c as well */ printf(“%x-%x-%x-%x\n”, u1.c[0], u1.c[1], u1.c[2], u1.c[3]); /* Changes the first 4 bytes of union u2 */ u2.i = 8; /* Changes all 8 bytes of union u2 */ u2.d = 2.35;

Union: Usage (1) If you can store a number of values in a union, a typical method is to specify a tag that tell you what is really stored in the union /* due to alignment */ sizeof(number) = 16; /* Store an int */ number.type = 0; number.u.i = 8; /* Store a float */ number.type = 1; number.u.f = 8.2; /* Store a double */ number.type = 2; number.u.d = 10.5; struct Number { /* 0: int * 1: float * 2: double */ int type; union { int i; float f; double d; } u; } number;

Union: Usage (2) struct Number { /* Thus we can store different type /* 0: int * 1: float * 2: double */ int type; union { int i; float f; double d; } u; } number; /* Thus we can store different type * of numbers in an array */ struct Number A[5]; A[0].type = 0; A[0].u.i = 2; A[1].type = 1; A[1].u.f = 2.3; A[2].type = 2; A[2].u.d = 3.4; A[3].type = 2; A[3].u.d = 5.8; A[4].type = 0; A[4].u.i = 4;