Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations

Presentation on theme: "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."— Presentation transcript:

1 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

2 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 ( ; )

3 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

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

5 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)*/

6 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.

7 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 *.

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

9 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.

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

11 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.

12 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.

13 /* 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; }

14 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

15 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.

16 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.

17 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; }

18 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.

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

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

21 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.

22 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.

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

24 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.

25 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

26 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.

27 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.

28 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***

29 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.***

30 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.

31 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.

32 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.

33 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.

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

Download ppt "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."

Similar presentations

Ads by Google