Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Structures Dale Roberts, Lecturer Computer Science, IUPUI.

Slides:



Advertisements
Similar presentations
1 Chapter 10 - Structures, Unions, Bit Manipulations, and Enumerations Outline 10.1Introduction 10.2Structure Definitions 10.3Initializing Structures 10.4Accessing.
Advertisements

StructuresStructures Systems Programming. Systems Programming: Structures 2 Systems Programming: 2 StructuresStructures Structures Structures Typedef.
StructuresStructures Systems Programming. StructuresStructures Structures Structures Typedef Typedef Declarations Declarations Using Structures with Functions.
2007 Pearson Education, Inc. All rights reserved C Structures, Unions, Bit Manipulations and Enumerations.
Case Study: Focus on Structures Math 130 Lecture 21 B Smith: 10/04: Required 35 minutes to complete. 15 minutes was spent returning test 2 and completing.
2000 Prentice Hall, Inc. All rights reserved. 1 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 Introduction Structures –Collections of related.
EASTERN MEDITERRANEAN UNIVERSITY EENG212 ALGORITHMS & DATA STRUCTURES Structures in C.
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.
2007 Pearson Education, Inc. All rights reserved C Structures, Unions, Bit Manipulations and Enumerations.
2000 Deitel & Associates, Inc. All rights reserved. Chapter 16 – Bits, Characters, Strings, and Structures Outline 16.1Introduction 16.2Structure Definitions.
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 Structures Basics of structures Typedef. Data Hierarchy Byte –8 bits (ASCII character ‘A’ = ) Field –Group of characters (character string “Fred”)
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.
CS1061: C Programming Lecture 21: Dynamic Memory Allocation and Variations on struct A. O’Riordan, 2004, 2007 updated.
Programming Languages -1 (Introduction to C) structures Instructor: M.Fatih AMASYALI
Kernighan/Ritchie: Kelley/Pohl:
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 - Pointers Outline 7.1Introduction 7.2Pointer.
 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,
Lesson 6 - Pointers Outline Introduction Pointer Variable Declarations and Initialization Pointer Operators Calling Functions by Reference Using the const.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 7 - Pointers Outline 7.1Introduction 7.2Pointer Variable Declarations and Initialization 7.3Pointer.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 10 - Structures, Unions, Bit Manipulations, and Enumerations Outline 10.1Introduction 10.2Structure.
CCSA 221 Programming in C CHAPTER 14 MORE ON DATA TYPES 1 ALHANOUF ALAMR.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
 2007 Pearson Education, Inc. All rights reserved C Pointers.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 10 - C Structures, Unions, Bit Manipulations,
Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR.
Fundamentals of C and C++ Programming Simple data structures Pointers.
Programming Languages -1 (Introduction to C) structures
16. STRUCTURES, UNIONS, AND ENUMERATIONS. Declaring Structures A structure is a collection of one or more components (members), which may be of different.
 2007 Pearson Education, Inc. All rights reserved C Structures, Unions, Bit Manipulations and Enumerations.
Pointers. Pointer Variable Declarations and Initialization Pointer variables – Contain memory addresses as their values – Normal variables contain a specific.
C Lecture Notes 1 Structures & Unions. C Lecture Notes Introduction Structures –Collections of related variables (aggregates) under one name Can.
Chapter 10 Structures, Unions, Bit Manipulations, and Enumerations Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering.
C How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Topics memory alignment and structures typedef for struct names bitwise & for viewing bits malloc and free (dynamic storage in C) new and delete (dynamic.
Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function.
1 Lecture 12 Pointers and Strings Section 5.4, ,
1 EPSII 59:006 Spring HW’s and Solutions on WebCT.
1 Lecture 8 Pointers and Strings: Part 2 Section 5.4, ,
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI N305 Structures Declarations.
 2000 Prentice Hall, Inc. All rights reserved Introduction Structures –Collections of related variables (aggregates) under one name Can contain.
StructureStructure. Outline Introduction Structure Definitions Initializing Structures Accessing Members of Structures Using Structures with Functions.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
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 *
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
ME2008– W05 MID1- Reference 2016Q1- Source: Deitel /C- How To.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI
Chapter 7 - Pointers Outline 7.1 Introduction
Structure, Unions, typedef and enumeration
C Structures, Unions, Bit Manipulations and Enumerations
Chapter 7 - Pointers Outline 7.1 Introduction
C Structures, Unions, Bit Manipulations and Enumerations
File Processing (Cont.) and Structures
CSC113: Computer Programming (Theory = 03, Lab = 01)
C Structures, Unions, and Enumerations
C Structures, Unions, Bit Manipulations and Enumerations
Chapter: 7-12 Final exam review.
CS111 Computer Programming
C Structures, Unions, Bit Manipulations and Enumerations
Structures Declarations CSCI 230
Presentation transcript:

Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Structures Dale Roberts, Lecturer Computer Science, IUPUI

Dale Roberts Introduction Structures A collection of one or more variables, possibly of different types, grouped together under a single name for continent handling. Commonly used to define records to be stored in files Combined with pointers, can create linked lists, stacks, queues, and trees Example: struct card { char *face; char *face; char *suit; }; char *suit; }; struct introduces the definition for structure card struct introduces the definition for structure card card is the structure name and is used to declare variables of the structure type card is the structure name and is used to declare variables of the structure type card contains two members of type char * card contains two members of type char * These members are face and suit

Dale Roberts Structure Definitions Example: A date consists of several parts, such as the day, month, and year, and the day of the year, and the month name struct date { int day; int month; int year; int year_date; char month_name[4]; }; date : the name of the structure, called structure tag. date : the name of the structure, called structure tag. day, month, …: the elements or variables mentioned in a structure are called members. day, month, …: the elements or variables mentioned in a structure are called members. struct information A struct cannot contain an instance of itself Can contain a member that is a pointer to the same structure type A structure definition does not reserve space in memory Instead creates a new data type used to declare structure variables

Dale Roberts Declaration of Variables of Structure Declarations method 1:declared like other variables: declare tag first, and then declare variable. struct card { char *face; char *suit; }; struct card oneCard, deck[ 52 ], *cPtr; *cPtr; method 2:A list of variables can be declared after the right brace and use comma separated list: struct card { char *face; char *suit; } oneCard, deck[ 52 ], *cPtr; method 3:Declare only variables. struct { char *face; char *suit; } oneCard, deck[ 52 ], *cPtr; struct date { }; struct date d1, d2, d3, d4, d5; struct date { } d1, d2, d3; struct date d4, d5; struct { } d1, d2, d3, d4, d5;

Dale Roberts Structure Definitions Valid Operations Assigning a structure to a structure of the same type Taking the address ( & ) of a structure Accessing the members of a structure Using the sizeof operator to determine the size of a structure Initialization of Structures Initializer lists Example: struct card oneCard = { "Three", "Hearts" }; struct card oneCard = { "Three", "Hearts" }; Example: struct date d1 = {4, 7, 1776, 186, “Jul”}; struct date d2 = {4, 7, 1776, 186, {‘J’,’u’,’l’,’\0’}}; Assignment statements Example: card threeHearts = oneCard;

Dale Roberts Accessing Members of Structures Accessing structure members Dot (. ) is a member operator used with structure variables Syntax: structure_name. member struct card myCard; struct card myCard; printf( "%s", myCard.suit ); printf( "%s", myCard.suit ); One could also declare and initialize threeHearts as follows: struct card threeHearts; threeHearts.face = “Three”; threeHearts.suit = “Hearts”; Arrow operator ( -> ) used with pointers to structure variables struct card *myCardPtr = &myCard; printf( "%s", myCardPtr->suit ); myCardPtr->suit is equivalent to (*myCardPtr).suit myCardPtr->suit is equivalent to (*myCardPtr).suit

Dale Roberts Structures Structure can be nested struct date { int day; int month; int year; int year_date; char month_name[4]; }; struct person { char name [NAME_LEN]; char address[ADDR_LEN}; long zipcode; long ss__number; double salary; struct date birthday; }; struct person emp; emp.birthday.month = 6; emp.birthday.year = 1776; Name Rule Members in different structure can have the same name, since they are at different position. struct s1 {.... char name[10];.... } d1; struct s2 {.... int name; } d2; struct s3 {.... int name; struct s3 t3; /* name */.... } d2; float name;

Dale Roberts Memory Layout Example: struct data1 { int day1; char month[9]; int year; }; Word (2 bytes) alignment machine – begins (aligns) at even address, such as PC, SUN workstation day1int2 bytes monthchar array9 bytes (hole)1 bytes yearint 2 bytes Quad (4 bytes) address alignment – begins (aligns) at quad address, such as VAX 8200 day1int4 bytes monthchar array9 bytes (hole)3 bytes yearint 4 bytes You must take care of hole, if you want to access data from very low level (i.e. low-level I/O, byte operations, etc.) integer 9 character (hole) integer 9 character (hole)

Dale Roberts sizeof Operator sizeof(struct tag) struct test { char name[5]; int i;/* assume int is 2 bytes */ char s; } t1, t2; main(){ printf(“sizeof(struct test) = %d\n”, sizeof (struct test)); printf(“address of t1 = %d\n”, &t1); printf(“address of t2 = %d\n”, &t2); printf(“address of t1.name = %d\n”, t1.name); printf(“address of t1.i = %d\n”, &t1.i); printf(“address of t1.s = %d\n”, &t1.s); }output: sizeof(struct test) = 10 address of t1 = 992 address of t2 = 1002 address of t1.name = 992 address of t1.i = 998 address of t1.s = bytes 5 bytes 1 byte (hole) 1 byte 1 byte (hole) bytes 5 bytes 1 byte (hole) 1 byte 1 byte (hole) t2 t1

Dale Roberts Using Structures With Functions Passing structures to functions Pass entire structure or pass individual members Both pass call by value It is not a good idea to pass a structure to or return from function. The better way is passing a pointer to the structure to the functions and returning a pointer from function. To pass structures call-by-reference Pass its address Pass reference to it To pass arrays call-by-value Create a structure with the array as a member Pass the structure

Dale Roberts Using Structures With Functions (cont.) Example: day_of_year(struct date *pd) { int i, day, leap; int i, day, leap; day = pd -> day; day = pd -> day; leap = pd->year%4 ==0 && pd->year %100 ==0 || pd->year%400 ==0; leap = pd->year%4 ==0 && pd->year %100 ==0 || pd->year%400 ==0; for (i=1; i month; i++) for (i=1; i month; i++) day += day_tab[leap][i]; return (day); return (day);} The declaration struct date *pd; says that pd is a pointer to a structure of the type date If p is a pointer to a structure, then p-> member_of_structure refers to the particular members, like pd -> year p-> member_of_structure is equivalent to (*p).member_of_structure p-> member_of_structure is equivalent to (*p).member_of_structure Notice: ‘.’ has higher precedence than ‘*’ ; *pd.year is wrong, since pd.year is not a pointer. Both -> and. associate from left to right. So p -> q -> member are (p->q)->member. Example: emp.birthday.month are (emp.birthday).month

Dale Roberts Using Structures With Functions (cont.) -> and. both are at the highest precedence (together with () for function and [] for array subscripts) -> and. both are at the highest precedence (together with () for function and [] for array subscripts) Example: struct { int *x; int *x; int *y; int *y; } *p; ++p->x; is equivalent to ++(p->x) /* increment x, not p */ ++p->x; is equivalent to ++(p->x) /* increment x, not p */ (++p)->x; /* increment p before access x */ (++p)->x; /* increment p before access x */ *p->y; /* fetch whatever y points to */ *p->y; /* fetch whatever y points to */ *p->y++; /* increments y after accessing whatever y point to */ *p->y++; /* increments y after accessing whatever y point to */ (*p->y)++; /* increments whatever y point to, just like *p->y++ */ (*p->y)++; /* increments whatever y point to, just like *p->y++ */ *p++->y; /* increments p after accessing whatever y point to */ *p++->y; /* increments p after accessing whatever y point to */

Dale Roberts typedef typedef Creates synonyms (aliases) for previously defined data types Use typedef to create shorter type names Example: typedef struct card *CardPtr; Defines a new type name CardPtr as a synonym for type struct card * typedef does not create a new data type while it o nly creates an alias typedef does not create a new data type while it o nly creates an alias Example: struct card { const char *face; const char *suit; }; typedef struct card Card; void fillDeck( Card * const, const char *[], const char *[] ); int main() { Card deck[ 52 ]; const char *face[] = {"Ace", "Deuce", "Three", "Four", "Five", "Six", Seven", "Eight", “Nine", "Ten", "Jack", "Queen", "King"}; const char *suit[] = { "Hearts", "Diamonds", "Clubs", "Spades"};.... fillDeck( deck, face, suit );.... } void fillDeck(Card * const wDeck, const char * wFace[], const char * wSuit[]) {.. }

Dale Roberts Unions union Memory that contains a variety of objects over time Only contains one data member at a time Members of a union share space Conserves storage Only the last data member defined can be accessed union declarations Same as struct union Number { int x; int x; float y; float y;}; union Number value; Valid union operations Assignment to union of same type: = Taking address: & Accessing union members:. Accessing members using pointers: ->

Dale Roberts 1/* Fig. 10.5: fig10_05.c 2 An example of a union */ 3#include 4 5union number { 6 int x; 7 double y; 8}; 9 10int main() 11{ 12 union number value; value.x = 100; 15 printf( "%s\n%s\n%s%d\n%s%f\n\n", 16 "Put a value in the integer member", 17 "and print both members.", 18 "int: ", value.x, 19 "double:\n", value.y ); value.y = 100.0; 22 printf( "%s\n%s\n%s%d\n%s%f\n", 23 "Put a value in the floating member", 24 "and print both members.", 25 "int: ", value.x, 26 "double:\n", value.y ); 27 return 0; 28} Put a value in the integer member and print both members. int: 100 double: Put a value in the floating member and print both members. int: 0 double: Define union Initialize variables Set variables Print Program Output

Dale Roberts Array of Structures Example: (before) char name[PERSON][NAMESIZE]; int tscore[PERSON] int math[PERSON] int english[PERSON] Initialization of structure array struct person_data{ } person[]={ {“Jane”,180,89,91}, {“Jane”,180,89,91}, {“John”,190,90,100}, {“John”,190,90,100}, }; /* similar to 2D array */ }; /* similar to 2D array */ Example: using separated arrays average (int tscore, int math, int eng, int n) { int i, total=0,mathtotal = 0, engtotal=0; for (i=0; i<n, i++) { total += *tscore++; mathtotal += *math++; engtotal += *eng++; } struct person_data{ char name[NAMESIZE]; int tscore; int math; int english; } person[PERSON]; (now)  Example: using pointer to structure average (struct person_data *person, int n) { int i, total=0,mathtotal = 0, engtotal=0; for (i=0; i<n, i++) { total += person->tscore; mathtotal += person->math; engtotal += person->eng; person++; } the inner brace is not necessary “Jane”,180,89,91, “John”,190,90,100,.... 

Dale Roberts Self-Reference Structure Dynamic Data Structure Data Structure: link list, tree, graph, … Example: Binary Tree Struct treeNode { char word[SIZE]; int count; struct treeNode *left; struct treeNode *right; /* or struct treeNode *left, *right; */ }; /* Inorder traversal */ tree_print(struct treeNode *p) { if (p!=NULL){ tree_print(p->left); printf(“....”, p->word,....); tree_print(p-> right); }}

Dale Roberts Link list Example: Struct listNode { Struct listNode { char word[SIZE]; int count; struct listNode *next;}; /* Inorder traversal */ list_print(struct listNode *p) { while (p!=NULL) { printf(“....”, p->word,....); printf(“....”, p->word,....); p = p->next; p = p->next; } }

Dale Roberts Bit Fields Bit field Member of a structure whose size (in bits) has been specified Enable better memory utilization Must be declared as int or unsigned Cannot access individual bits Declaring bit fields Follow unsigned or int member with a colon ( : ) and an integer constant representing the width of the field Example: struct BitCard { unsigned face : 4; unsigned face : 4; unsigned suit : 2; unsigned suit : 2; unsigned color : 1; unsigned color : 1;}; Unnamed bit field Field used as padding in the structure Nothing may be stored in the bits Unnamed bit field with zero width aligns next bit field to a new storage unit boundary struct Example { unsigned a : 13; unsigned : 3; unsigned b : 4; }

Dale Roberts Enumeration Constants Enumeration Set of integer constants represented by identifiers Enumeration constants are like symbolic constants whose values are automatically set Values start at 0 and are incremented by 1 Values can be set explicitly with = Need unique constant names Example: enum Months { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}; Creates a new type enum Months in which the identifiers are set to the integers 1 to 12 Enumeration variables can only assume their enumeration constant values (not the integer representations)

Dale Roberts 1/* Fig : fig10_18.c 2 Using an enumeration type */ 3#include 4 5enum months { JAN = 1, FEB, MAR, APR, MAY, JUN, 6 JUL, AUG, SEP, OCT, NOV, DEC }; 7 8int main() 9{9{ 10 enum months month; 11 const char *monthName[] = { "", "January", "February", 12 "March", "April", "May", 13 "June", "July", "August", 14 "September", "October", 15 "November", "December" }; for ( month = JAN; month <= DEC; month++ ) 18 printf( "%2d%11s\n", month, monthName[ month ] ); return 0; 21} 1 January 2 February 3 March 4 April 5 May 6 June 7 July 8 August 9 September 10 October 11 November 12 December

Dale Roberts Storage Management C supports 4 functions, malloc(), calloc(),free(), and cfree() for storage management malloc(n): malloc(n): allocate a node while its content is still ‘garbage’ n is an integer, indicating the size of memory in byte which you would like to allocate malloc() return a character pointer to that memory So, you have to use cast operator (type), to change the type of the pointer. Example: int *ip; ip = (int*) malloc(sizeof(int)); struct treeNode *tp; tp = (struct tnode *) malloc(sizeof(struct tnode));

Dale Roberts Storage Management (cont.) free(p): free(p): free() will release the memory allocated by malloc(). free() will release the memory allocated by malloc(). p is the pointer containing the address returning from malloc(). p is the pointer containing the address returning from malloc(). Example: int *ip; int *ip; ip = (int*) malloc(sizeof(int)); ip = (int*) malloc(sizeof(int)); free(ip);/* Question: can you free(ip) after ip++ ? */ Example: struct treeNode *tp; struct treeNode *tp; tp=(struct treeNode *)malloc(sizeof(struct treeNode )); tp=(struct treeNode *)malloc(sizeof(struct treeNode )); free(tp); When there is no further memory, malloc() will return NULL pointer. It is a good idea to check the returning value of malloc(). if ((ip=(int *)malloc(sizeof(int))) == NULL){ printf(“\nMemory is FULL\n”); exit(1);} When you free the memory, you must be sure that you pass the original address returning from malloc() to function free(). Otherwise, system exception may be happened

Dale Roberts Storage Management (cont.) calloc(n,size): calloc(n,size): calloc() allow you to allocate an n elements array of same data type. Because n can be an integer variable, you can use calloc() to allocate a dynamic size array. calloc() allow you to allocate an n elements array of same data type. Because n can be an integer variable, you can use calloc() to allocate a dynamic size array. n is the element number of array that you want to allocate. n is the element number of array that you want to allocate. size is the number of byte of each element. size is the number of byte of each element. Unlike malloc(), calloc() guarantees that memory contents are all zero Example: allocate an array of 10 elements int *ip; ip = (int*) calloc(10, sizeof(int)); *(ip+1) refer to the 2 nd element, the same as ip[1] *(ip+1) refer to the 2 nd element, the same as ip[1] *(ip+i) refer to the i+1 th element, the same as ip[i] *(ip+i) refer to the i+1 th element, the same as ip[i] Like malloc(), calloc() will return NULL, if no further memory is available. cfree(p): cfree() releases the memory allocated by calloc(). cfree() releases the memory allocated by calloc(). Example: cfree(ip);