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.

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.
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.
Programming in C Chapter 10 Structures and Unions
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.
SEE C GO Provisional Title. Syntax Types int, float, double, char, void Identifiers foo Operators + - * / ^ Delimiters ; {} () “” ‘’ Keywords return,
Dynamic memory allocation
An introduction to pointers in c
Chapter 6 Structures By C. Shing ITEC Dept Radford University.
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
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.
Structures in C.
CS1061: C Programming Lecture 21: Dynamic Memory Allocation and Variations on struct A. O’Riordan, 2004, 2007 updated.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures.
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 7 : September 8.
CP104 Introduction to Programming Structure II Lecture 32 __ 1 Data Type planet_t and Basic Operations Abstract Data Type (ADT) is a data type combined.
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
 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,
Chapter 12 C Data Structures Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 12 – Data Structures Outline 12.1Introduction.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 10 - Structures, Unions, Bit Manipulations, and Enumerations Outline 10.1Introduction 10.2Structure.
Chapter 12 Data Structure Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Custom Templatized Data Structures.
 2007 Pearson Education, Inc. All rights reserved C Data Structures.
Introduction to Data Structures Systems Programming.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 10 - C Structures, Unions, Bit Manipulations,
Learners Support Publications Classes and Objects.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
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.
 2007 Pearson Education, Inc. All rights reserved C Structures, Unions, Bit Manipulations and Enumerations.
Introduction to Data Structures Systems Programming Concepts.
Programming Practice 3 - Dynamic Data Structure
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.
1 EPSII 59:006 Spring HW’s and Solutions on WebCT.
+ Arrays & Random number generator. + Introduction In addition to arrays and structures, C supports creation and manipulation of the following data structures:
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
CNG 140 C Programming (Lecture set 12) Spring Chapter 13 Dynamic Data Structures.
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Linked Lists Outline Introduction Self-Referential Structures.
STRUCTURES. INTRODUCTION A structure is same as that of records. It stores related information about an entity. Structure is basically a user defined.
You learned how to declare pointer variables how to store the address of a variable into a pointer variable of the same type as the variable how to manipulate.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Chapter 12 – Data Structures
5.13 Recursion Recursive functions Functions that call themselves
12 C Data Structures.
12 C Data Structures.
Structure, Unions, typedef and enumeration
C Structures, Unions, Bit Manipulations and Enumerations
Introduction to Data Structures
Lecture 9 Structure 1. Concepts of structure Pointers of structures
C Structures, Unions, and Enumerations
C Structures, Unions, Bit Manipulations and Enumerations
Review & Lab assignments
Chapter: 7-12 Final exam review.
Presentation transcript:

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 to arrays. Structure definition: struct card { char *face; char *suit; }; Structure tagMembers Structure type

Basic Rules in Structures Members of the same structure must have unique names. But two different structures may contain members of the same name without conflict Each structure definition must end with a semicolon ( ; )

Restrictions on the member type in a structure A member of a structure may not be: 1. a Function 2. a type of void 3. nest a structure of its own type

Example struct employee { char firstName[ 20 ]; char lastName[ 20 ]; int age; char gender; double hourlySalary; }; /*Notice the different types of the members*/

Example 2: Self-referential structure struct employee2 { char firstName[ 20 ]; char lastName[ 20 ]; int age; char gender; double hourlyRate; struct employee2 person; /* Error */ struct employee2 *ePtr; /*Allowed*/ }; /* a structure cannot contain an instance of itself (person)*/

Initializing structures struct card a = { Three, Hearts}; Will creates variable a to be of type struct card and initializes member face to Three and member suit to Hearts ** If there are few initializers in the list than members in structure, the remaining members are automatically initialized to 0.

Accessing Members of Structures The structure member operator and point operator. They are often called : The dot (.)and arrow(->) operators Respectively. printf( %s, a.suit ); printf( %s, aPtr->suit); /* this one =*/ printf( %s, (*aPtr).suit); ( ) is needed here because of. has higher precedence than *.

Example 3 High-performance card shuffling and dealing simulation(Example name cards.c in Linux)

In That Program Function fillDeck initializes the Card array in order with Ace through King of each suit. The Card array is passed to function shuffle Function shuffle takes an array of 52 Card structures as an argument. The function loops through the 52 cards(0- 51). A number 0-51 is picked randomly.

Structures vs. Class in C++ In C++, a struct is the same as a class, except all its members are by default public.

Union Similar to structure, union was introduced to save memory space. For those structure in which two or more fields can never be simultaneously active, we can use union to do the job. Another obvious advantage of union is that the members of the union do not have to have the same type.

Example for union On the Linux subdirectory cs315 with name: union1.c and union1 for the.exe file. Both x and y share the same memory and they cannot be both active at the same time. ***Nowadays, union is no longer a very useful function in C because of the low price of memory system.

/* Fig. 10.5: fig10_05.c An example of a union */ #include union number { int x; double y; }; int main() { union number value; value.x = 100; printf( "%s\n%s\n%s%d\n%s%f\n\n", "Put a value in the integer member", "and print both members.", "int: ", value.x, "double:\n", value.y ); value.y = 100.0; printf( "%s\n%s\n%s%d\n%s%f\n", "Put a value in the floating member", "and print both members.", "int: ", value.x, "double:\n", value.y ); return 0; }

typedef typedef is a useful keyword 1. It is a mechanism for creating synonyms 2. Name for structure types are often use it to create a shorter type names. Example: typedef struct card Card; Here Card will replace struct card

Another example for typedef The following program segment typedef struct { char *face; char *suit; } Card; will create the structure type Card without the need for a separate typedef statement typedef can make a program more portable.

rand and srand rand is a function that generates pseudo- random numbers. It is so called pseudo is because the sequence repeats itself each time the program is executed. srand is the function that takes an unsigned integer argument and seeds function rand to produce a different sequence of random numbers for each execution of the program. The srand is called randomizing.

Example #include int main ( ) { int i; unsigned seed; printf( Enter seed: ); scanf( %u, &seed ); for ( i = 1; i <= 10; i++ ) { printf( %10d, 1 + ( rand ( ) % 6 ) ); if ( i% 5 == 0 ) printf ( \n ); } return 0; }

Use computer clock to create random numbers srand ( time( NULL ) ); will cause the computer to read its clock to obtain the value for the seed automatically. Here function time returns the current time of the day in seconds. Normally, function time provides a string representing the time of day. Null disable this capability for a specific call to time.

The ? : Operator Format: TestExpr ? YesExpr : NoExpr If TestExpr is true, YesExpr is evaluated, otherwise, NoExpr is evaluated. Example: X = ( Y > Z ) ? Y : Z

Data Structure and Dynamic Memory Allocation Linked list Stacks Queues Trees Dynamic Memory Allocation We mainly talk about the Dynamic Memory Allocation

malloc and free & sizeof Purpose: Creating and maintaining dynamic data structure requires dynamic memory allocation---the ability for a program to obtain more memory space at execution time to hold new nodes, and to release space no longer needed. Function malloc normally used with sizeof operator.

Example newPtr = malloc( sizeof ( struct node )); Evaluates sizeof ( struct node ) to determine the size in bytes of a structure of type struct node, allocates a new area in memory of sizeof ( struct node ) bytes, and stores a pointer to the allocated memory in variable newPtr. If no memory is available, malloc returns a NULL pointer.

free free ( newPtr ); free will deallocates memory, i.e., to free the memory dynamically allocated by the preceding malloc call.

Self-Referential Structure Let look a structure example again struct node { int date; struct node *nextPtr; }; structure type---struct node The second member of the structure is a pointer---nextPtr. We refer to the second member nextPtr as a link.

Self-Referential Structure nextPtr can be used to tie a structure of type struct node to another structure of the same type. Self-Referential structure can be linked together to form useful data structures such as: 1. Lists 2. Queues 3. Stacks 4. Trees

Self-Referential Structures Lists This back-slash represents NULL pointer. struct A struct B It also indicates that the second struct doesnt point to another structure.

Dynamic Memory Allocation 1. Function malloc and free and operator sizeof sizeof is a compile-time unary operator. It returns an unsigned integer. Example: sizeof (int) is used to determine an integer is stored as 2 or 4 bytes on a particular computer. *** Using sizeof is not a function and it will not cause any execution-time overhead.

Dynamic Memory Allocation Function malloc takes an argument the number of bytes to be allocated, and it will return a pointer of type void* to the allocated memory A viod* pointer can be assigned to any pointer type. Example: newPtr = malloc (sizeof ( struct node )) ; *** If no memory is available, malloc returns a NULL***

Function free Function free deallocates memory ---the memory is returned to the system. Example: To free the dynamic memory allocated by the preceding malloc call, free ( newPtr ); ***Common misconception: Assuming the size of a structure is the sum of the sizes of its members.***

Memory Leak Not returning dynamically allocated memory when it is no longer needed can cause the system run out of memory prematurely. Similarly, to free the memory that not allocated by malloc or refer to the memory that already been freed will cause program errors, too.

Linked Lists A linked list is a linear collection of self- referential structures, called nodes.... Pointer to access the linked list NULL StartPtr ***Linked list nodes are normally not stored contiguously. Fat in hard drive file management is a good example.

Linked Lists Vs Arrays 1. Linked lists are dynamic, so the length of a list can increase or decrease as necessary. The size of an array, however, cannot be altered once memory is allocated.

Example --- List This example shows how to use malloc, free and sizeof operator in operating and maintaining a list. Pay attention to the dynamic memory allocations.

*sptrpreviousPtr CurrentPtr newPtr AB C DE NULL----->. Insertion of a node contain c to the ordered list