C Structures What is a structure A structure



![Example • struct employee { • char first. Name[ 20 ]; • char last. Example • struct employee { • char first. Name[ 20 ]; • char last.](https://slidetodoc.com/presentation_image_h/19f986323fc84bb898ca99b278148777/image-4.jpg)






























- Slides: 34

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: Structure tag struct card { char *face; char *suit; }; Structure type Members

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 first Name 20 char last Example • struct employee { • char first. Name[ 20 ]; • char last.](https://slidetodoc.com/presentation_image_h/19f986323fc84bb898ca99b278148777/image-4.jpg)
Example • struct employee { • char first. Name[ 20 ]; • char last. Name[ 20 ]; • int age; • char gender; • double hourly. Salary; • }; • /*Notice the different types of the members*/

Example 2: Self-referential structure • struct employee 2 { • char first. Name[ 20 ]; • char last. Name[ 20 ]; • int age; • char gender; • double hourly. Rate; • struct employee 2 person; /* Error */ • struct employee 2 *e. Ptr; /*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”, a. Ptr->suit); /* this one =*/ • printf( “%s”, (*a. Ptr). 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 fill. Deck 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(051). 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 cs 315 with name: union 1. c and union 1 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: fig 10_05. c An example of a union */ #include <stdio. h> • • union number { int x; double y; }; • • • • • int main() { union number value; value. x = 100; printf( "%sn%s%dn%s%fnn", "Put a value in the integer member", "and print both members. ", "int: ", value. x, "double: n", value. y ); value. y = 100. 0; printf( "%sn%s%dn%s%fn", "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 srand • rand is a function that generates pseudorandom 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 <stdio. h> #include <stdlib. h> int main ( ) { int i; unsigned seed; printf( “Enter seed: “); scanf( “%u, &seed ); for ( i = 1; i <= 10; i++ ) { printf( “%10 d”, 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: Test. Expr ? Yes. Expr : No. Expr • If Test. Expr is true, Yes. Expr is evaluated, otherwise, No. Expr 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 • new. Ptr = 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 new. Ptr. • If no memory is available, malloc returns a NULL pointer.

free • free ( new. Ptr ); • 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 *next. Ptr; }; structure type---struct node The second member of the structure is a pointer---next. Ptr. • We refer to the second member next. Ptr as a link.

Self-Referential Structure • next. Ptr 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 struct B 15 . 10 struct A This back-slash represents NULL pointer. It also indicates that the second struct doesn’ point to another structure.

Dynamic Memory Allocation • • • 1. Function malloc and free and operator 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: • new. Ptr = 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 ( new. Ptr ); • ***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 selfreferential structures, called nodes. 17 . 29 . . Start. Ptr 36 . 48 NULL Pointer to access the linked list ***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.

Insertion of a node contain “c” to the ordered list . *sptr A . previous. Ptr . B . . Current. Ptr . D new. Ptr C . . NULL-----> E .