Lecture 13 Structs.

Slides:



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

Chapter 10 C Structures, Unions, Bit Manipulations and Enumerations Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc.
C Structures What is a structure? A structure is a collection of related variables. It may contain variables of many different data types---in contrast.
Chapter 10 C Structures, Unions, Bit Manipulations, and Enumerations.
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.
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.
 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,
Enum, Struct, & Union typedef - a type definition, typedef, gives a name to a data type by creating a new type that can then be used anywhere a type is.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 10 - Structures, Unions, Bit Manipulations, and Enumerations Outline 10.1Introduction 10.2Structure.
Lecture No: 16. The scanf() function In C programming language, the scanf() function is used to read information from standard input device (keyboard).
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 Programming Tutorial – Part I CS Introduction to Operating Systems.
Lecturer: Omid Jafarinezhad Sharif University of Technology Department of Computer Engineering 1 Fundamental of Programming (C) Lecture 8 Structures, Unions,
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
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.
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.
 2007 Pearson Education, Inc. All rights reserved C Structures, Unions, Bit Manipulations and Enumerations.
Data Structure and c K.S.Prabhu Lecturer All Deaf Educational Technology.
Chapter 10 Structures, Unions, Bit Manipulations, and Enumerations Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering.
Structures and Unions in C Alan L. Cox
Introduction to Computers and Programming Class 24 Structures (structs) Professor Avi Rosenfeld.
1 Lecture10: Structures, Unions and Enumerations 11/26/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
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.
Introduction to Programming Lecture 11: struct & typedef & enum.
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.
Lecture 10 union, enumeration, bit
LESSON 06.
Chapter 7: User-Defined Functions II
Structures, Unions, Enumerations
User Defined Data Types
Structures.
Structure, Unions, typedef and enumeration
C Structures, Unions, Bit Manipulations and Enumerations
C Programming Tutorial – Part I
Structures and Unions in C
C Structures, Unions, Bit Manipulations and Enumerations
Module 2 Arrays and strings – example programs.
សាកលវិទ្យាល័យជាតិគ្រប់គ្រង National University of Management
Programmazione I a.a. 2017/2018.
Instructor: Ioannis A. Vetsikas
Lecture 21 Structs.
DATA HANDLING.
Introduction to Programming
Structure.
Structures Lesson xx In this module, we’ll introduce you to structures.
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
Lecture 10 Arrays.
2017 Jan Sun Mon Tue Wed Thu Fri Sat
Classes and Objects.
Chapter: 7-12 Final exam review.
Chapter 1: Introduction to Data Structures(8M)
Jan Sun Mon Tue Wed Thu Fri Sat
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
C Structures, Unions, Bit Manipulations and Enumerations
Pointers Pointers point to memory locations
CS 240 – Lecture 7 Boolean Operations, Increment and Decrement Operators, Constant Types, enum Types, Precedence.
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
Pointers, Dynamic Data, and Reference Types
Lecture 7: Types (Revised based on the Tucker’s slides) 10/4/2019
Structures, Unions, and Enumerations
Presentation transcript:

Lecture 13 Structs

Introduction Our variables until now Single variable int i, char c, float f Set of same type elements: Array int a[10], char c[20] If data are not same type, but related? Example: Information about students Student Name Student Family Name Student Number Student Grade

Introduction How to save the student information? 1- Use separated variables st_name[20]; st_fam_name[20];  char id; grade;  int 2- Put them altogether, they are related Use struct

Structure Basics A structure is a collection of data values, called data members, that form a single unit. Unlike arrays, the data members can be of different types.

struct: version 1 Set of related variables struct in C (version 1) Each variable in struct has its own type struct in C (version 1) struct { <variable declaration> } <identifier list>;

struct (version 1): Example char char st_name[20]; st_fam_name[20]; int id; int grade; } st1; We declare a variable st1 Type of st1 is struct id is a member of the struct grade is a member of the struct

struct (version 1): Example char char st_name[20]; st_fam_name[20]; int id; int grade; } st1, st2, st3; We declare three variables: st1, st2, st3 Type of st1, st2, st3 is the struct In this model, we cannot reuse the struct definition in other location (e.g., input of function)

struct: Version 2 struct in C (version 2) struct <tag> { <variable declaration> }; struct <tag> <identifiers>;

struct (version 2): Example student { st_name[20]; st_fam_name[20]; struct char int id; int grade; }; struct student st1, st2, st3; We define a struct with tag student We don’t allocate memory, it is just definition We declare variables st1, st2, st3 from student

Declaring Structures (struct) The name "employee" is called a structure tag Variables declared within the braces of the structure definition are the structure’s members struct employee { char firstName[ 20 ]; char lastName[ 20 ]; int age; char gender; double hourlySalary; }; struct employee Ali, emp[10]; struct employee { char firstName[ 20 ]; char lastName[ 20 ]; int age; char gender; double hourlySalary; } Ali, Sara, empDTS[20]; struct employee Reza, *emp; struct { char firstName[ 20 ]; char lastName[ 20 ]; int age; char gender; double hourlySalary; } Ali;

Declaring Structures (struct) Members of the same structure type must have unique names, but two different structure types may contain members of the same name without conflict Each structure definition must end with a semicolon struct employee { char Name[ 20 ]; char Name[ 20 ]; // Error!!! int age; char gender; double hourlySalary; } Ali, Sara, empDTS[20]; struct employee Reza, *emp; struct Student { char Name[ 20 ]; // OK int age; char gender; }; struct Student Ce40153[80];

Structures as New Data Type When we define a new struct, in fact we are define a new data type Then we use the new data type and define variables So, we need to learn how to work it Access to members Operators for struct Pointer to struct struct in functions Array of struct

Size of struct char st_fam_name[20]; int id; int grade; struct std_info{ char st_name[20]; char st_fam_name[20]; int id; int grade; }; struct std_info st1, st2, sizeof(struct std_info)  ? st3; sizeof(st1)  ?

Using struct We should declare variables from struct type  Versions 1, 2, 3.1, 3.2 How to access to the members of struct <struct variable>.<element name>  st1.st_name is a array of char in struct st1  st2.grade is a int variable in struct st2

Example

struct initialization

struct initialization Similar to array initialization information st1 = {"Ali", "Karimi", “Ali” is assigned to st_name “Karimi” is assigned to st_fam_name 9222 is assigned to id 10 is assigned to grade 9222, 10}; Order of values should be exactly the order of the members The number of values must be <= the number of members  Initial values cannot be assigned in struct definition

Initializing Structures x y r color 5.0 width 10.0 height

Nested struct struct date_type{ int d, m, y; }; student{ name[20]; fam_name[20]; struct char char int int id; grade; struct date_type }; date;

Nested struct struct student st1 = {"A","B",1,10,{2,3,1368}}; st2.name = "C"; st2.fam_name = "D"; st2.id = 2; = st2.grade 15; st2.date.rooz st2.date.mah st2.date.sal = 10; = 5; = 1390;

Declaring Structures (struct) A structure cannot contain an instance of itself For example, a variable of type struct employee cannot be declared in the definition for struct employee A pointer to struct employee, however, may be included A structure containing a member that is a pointer to the same structure type is referred to as a self-referential structure struct employee2 { // … double hourlySalary; struct employee2 person; /* ERROR */ struct employee2 *ePtr; /* pointer */ };

Structure and operators

struct: Copy and Assignment date_type{ rooz, mah, struct int }; sal; date_type d1, d2 = {2, 1, 1360}; /* Copy all data from d2 to d1. */ d1 = d2; /* d1.rooz = d2.rooz; d1.mah d1.sal = d2.mah; = d2.sal; */

struct: Copy and Assignment struct test_type{ char name[10]; int id[10]; }; struct 3}}; test_type d1, d2 = {"ABC", {1, 2, d1 = d2; /* d1.name d1.id = "ABC"; = {1, 2, 3}; */

struct: Comparing We cannot compare struct variables ==, <=, <, >, >= cannot be used for struct information st1, st2; if(st1 <= st2){ ... } // Compile Error

struct: Comparing We can compare members of structs

Array of struct: Definition  struct is a type  We can define array of struct

.ﺪﻨﻛ ﺪﻴﻟﻮﺗ ﺍﺭ ﺖﺳﺍ ﻦﻴﮕﻧﺎﻴﻣ ﺯﺍ ﺮﺘﺸﻴﺑ 34 ﺍﺭ ﻥﺎﻳﻮﺠﺸﻧﺍﺩ ﻩﺮﻤﻧ ﻭ ﻩﺭﺎﻤﺷ ﻪﻛ ﻱﺍﻪﻣﺎﻧﺮﺑ ﺎﻬﻧﺁ ﻩﺮﻤﻧ ﻪﻛ ﻲﻧﺎﻳﻮﺠﺸﻧﺍﺩ ﺖﺴﻴﻟ ﻭ ﺩﺮﻴﮕﺑ .ﺪﻨﻛ ﺪﻴﻟﻮﺗ ﺍﺭ ﺖﺳﺍ ﻦﻴﮕﻧﺎﻴﻣ ﺯﺍ ﺮﺘﺸﻴﺑ

Quick overview We can define new data type using Structure. Syntax of structure definition is:

Example

Example

Example

#include <stdio.h> 36 #include <stdio.h> .ﺩﺮﻴﮕﺑ ﺍﺭ ﻥﺎﻳﻮﺠﺸﻧﺍﺩ ﺯﺍ ﺖﺴﻴﻟ ﻚﻳ ﻪﻛ ﻱﺍﻪﻣﺎﻧﺮﺑ ﻮﺠﺸﻧﺍﺩ ﺮﮔﺍ ﻭ ﺩﺮﻴﮕﺑ ﻲﻳﻮﺠﺸﻧﺍﺩ ﻩﺭﺎﻤﺷ ﻚﻳ ﺲﭙﺳ .ﺪﻫﺩ ﻥﺎﺸﻧ ﺍﺭ ﻱﻭ ﺕﺎﻋﻼﻃﺍ ﺖﺳﺍ ﺖﺴﻴﻟ ﺭﺩ int main(void){ struct std{ char name[20]; int id; int grade; }; const int num = 25; struct std std_arr[num]; int sid, i; for(i = 0; i < num; i++){ printf("Enter Name, ID and grade\n"); std_arr[i].name); &(std_arr[i].id)); &(std_arr[i].grade)); scanf("%s", scanf("%d", }

printf("Enter Search scanf("%d", &sid); 37 ID: "); for(i = 0; i < num; i++) if(std_arr[i].id == sid){ printf("Found:\n"); printf("Name = %s\n", std_arr[i].name); printf("ID = %d\n", std_arr[i].id); printf("Grade = %s\n", std_arr[i].grade); } return 0;

Pointer and Structure

Pointer to struct: Definition A variable of struct type is a variable It has address, we can have pointer to it std{ id; grade; struct int int }; struct struct std st1; std *ps; ps = &st1;

Pointer to struct: Usage (Version 1) We can use *pointer method *ps means the content of the address that ps refers to there  it is struct (*ps).id is the member of struct that ps refers to it (*ps).grade is the member of struct that ps refers to it

Pointer to struct: Usage (Version 2) We can use “->" method struct std{ int id; int grade; }; struct std st1, *ps; ps = &st1 int y = ps->id; int z = ps->grade; // (*ps).id // (*ps).grade

Example

Exapmle ﻞﺻﺎﺣ ﻭ ﺩﺮﻴﮔﻲﻣ ﺍﺭ ﺎﻳﻮﮔ ﺩﺪﻋ ﻭﺩ ﻪﻛ ﻲﻌﺑﺎﺗ .ﺪﻨﻛﻲﻣ ﺪﻴﻟﻮﺗ ﺍﺭ ﺎﻬﻧﺁ ﻖﻳﺮﻔﺗ ﻭ ﻊﻤﺟ Exapmle

Structures and Function

struct & Functions struct is a type so It can be used In input parameter list of functions Call by value Call by reference In return type of functions void f(struct std s1); // call by value input void g(struct std *s2); // call by reference struct std h(void); // return type

struct & Functions: Example struct as call by value input parameter

struct & Functions: Example struct as call by reference input parameter

struct & Functions: Example struct as output of function information create_st_info(void){ information scanf("%s", scanf("%s", scanf("%d", scanf("%d", return tmp; tmp; tmp.name); tmp.fam_name); &tmp.id); &tmp.grade); } //----- Calling the function information st1; st1 = create_st_info(); ----

Scope of struct definition A struct can be used only In the defined scope After definition  if sruct is defined in a function It can be used only in the function No other function knows about it  If struct is defined as a global It can be used in all function after the definition

Scope of struct variables The scope of struct variables are the same other variables Member variables are local to the structure. If struct variable is global Initialized to zero and visible to the functions after its declaration If struct variable is automatic local There is not any initial value, destroyed when the block finishes If struct variable is static Kept in memory until program finishs

ﻭ ﺩﺮﻴﮕﺑ ﺍﺭ ﺎﻫﻥﺎﻣﺯ ﺯﺍ ﻪﻋﻮﻤﺠﻣ ﻚﻳ ﻱﺍﻪﻣﺎﻧﺮﺑ #include <stdio.h> ﻭ ﺩﺮﻴﮕﺑ ﺍﺭ ﺎﻫﻥﺎﻣﺯ ﺯﺍ ﻪﻋﻮﻤﺠﻣ ﻚﻳ ﻱﺍﻪﻣﺎﻧﺮﺑ ،ﺖﻋﺎﺳ ﻞﻣﺎﺷ ﻥﺎﻣﺯ ﺮﻫ .ﺪﻨﻛ ﺐﺗﺮﻣ ﺍﺭ ﺎﻬﻧﺁ .ﺖﺳﺍ ﻪﻴﻧﺎﺛ ﻭ ﻪﻘﻴﻗﺩ struct time{ int hour; int min; int sec; }; /* 1: t1 > t2, 0: int time_cmp(struct time t1, struct t1 = t2, -1: t1 < t2 */ time t2){ if(t1.hour > t2.hour) return 1; else if(t2.hour > t1.hour) return -1; else if(t1.min return 1; else if(t2.min return -1; else if(t1.sec return 1; else if(t2.sec return -1; else return 0; > t2.min) > t1.min) > t2.sec) > t1.sec) }

void time_swap(struct time *t1, struct time tmp; struct time *t2){ tmp = *t1; *t1 *t2; *t2 tmp; } /* Find index of max element */ int rec_max(struct time time_arr[], int start, int int tmp, res; if(start == end) res = start; else{ tmp = rec_max(time_arr, start + 1, end); if(time_cmp(time_arr[start], time_arr[tmp]) res = start; else res = tmp; } return res; end){ >= 0) }

/* Recursively sort array from start to end */ void rec_sort(struct time time_arr[], int start, int int max; if(start == end) return; end){ max = rec_max(time_arr, start, end); time_swap(&(time_arr[start]), &(time_arr[max])); rec_sort(time_arr, start + 1, end); } /* Print Array elements void print_array(struct from start to end */ time time_arr[], int start, int end){ for(int i = start; i <= end; i++) printf("%d:%d:%d, ", time_arr[i].hour, time_arr[i].min, time_arr[i].sec); printf("\n"); }

int main(void){ struct time ta[5] = {{4, 0, 1}, {6, 1, 0}, {2, 2, 1}, 4, 7}, {8, 5, 4}}; print_array(ta, rec_sort(ta, 0, print_array(ta, 0, 4); 4); 0, 4); return 0; }

Enum Introduction Some data are naturally ordered Days of week Months of year We want to use the order, e.g. The number of visitors per day The salary per month We need an array visitors[0]  The number of visitors in Saturday visitors[1]  The number of visitors in Sunday

Enum Introduction Enumeration is a mechanism to assign a name for each number E.g. visitors[saturday], visitors[friday] salary[april], salary[may]

enum enum is used to define a set of names and their corresponding numbers enum tag {name_1, name_2, …, name_N} tag is the enumeration type We use it to define variables name_1 = 0 name_2 = 1 name_i = (name_(i-1)) + 1

enum enum week {sat, sun, mon, tue, wed, thu, fri}; sat = 0, sun = 1, mon = 2, …, fri = 6 enum year {jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, des};  jan = 0, feb = 1, …, nov = 10, des = 11

enum We can assign the numbers enum week {sat = 1, sun, wed, thu, fri}; mon, tue, sat = 1, sun = 2, mon = 3, …, fri = 7 enum condition {False = 0, True, No = 0, Yes, Ghalat = 0, Dorost}; False = No = Ghalat = 0 True = Yes = Dorost = 1

enum After definition of an enumeration We can use the tag to declare variables We can use the names to assign values to the variables enum week {sat, sun, mon, tue, wed, thu, fri}; enum week day = sat; for(day = sat; day <= fri; day++)

Example: Read the number of visitors enum week {sat, sun, mon, tue, wed, thu, fri}; int visitors[7]; enum week day; sat; day <= fri; for(day = day++) scanf("%d", &visitors[day]);

Enumeration Values in an enum start with 0, unless specified otherwise, and are incremented by 1 The identifiers in an enumeration must be unique The value of each enumeration constant of an enumeration can be set explicitly in the definition by assigning a value to the identifier Multiple members of an enumeration can have the same constant value

Unions A union is a derived data type—like a structure—with members that share the same storage space a union shares the space instead of wasting storage on variables that are not being used The members of a union can be of any data type The number of bytes used to store a union must be at least enough to hold the largest member Only one member, and thus one data type, can be referenced at a time

Unions representation c union myDataUnion { int i; char c; float f; } u1, u2; union myDataUnion u3; u1.i = 4; u1.c = ’a’; i f

Unions The operations that can be performed on a union are the following: assigning a union to another union of the same type taking the address (&) of a union variable accessing union members using the structure member operator and the structure pointer operator Unions may not be compared using operators == and != same as the structures

Unions In a declaration, a union may be initialized with a value of the same type as the first union member union a { int a; // OK char b[4]; }; union a x = {10}; printf("%d", x.a);

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

Tagged Unions Tag every value with its case enum Union_Tag {IS_INT, IS_CHAR}; struct TaggedUnion { enum Union_Tag tag; union { int i; char c; } data; }; Enum must be external to struct, so constants are globally visible Struct field must be named

Bit-field Structures C enables you to specify the number of bits in which an unsigned or int member of a structure or union is stored This is referred to as a bit field Bit fields enable better memory utilization by storing data in the minimum number of bits required Bit field members must be declared as int or unsigned A bit field is declared by following an unsigned or int member name with a colon (:) and an integer constant representing the width of the field (i.e., the number of bits in which the member is stored)

Bit-field Structures Notice that bit field members of structures are accessed exactly as any other structure member struct Flags { int f1:3; unsigned int f2:1; unsigned int f3:2; } foo; foo.f1 = -2; foo.f2 = 1; foo.f3 = 2; 1 … f1 f2 f3 …8 bit …

Notes of caution Bit-field manipulations are machine dependent Attempting to access individual bits of a bit field as if they were elements of an array is a syntax error. Bit fields are not "arrays of bits" Attempting to take the address of a bit field (the & operator may not be used with bit fields because they do not have addresses) Although bit fields save space, using them can cause the compiler to generate slower-executing machine-language code. This occurs because it takes extra machine language operations to access only portions of an addressable storage unit.