1 / 54

Structure and User Defined Type

Structure and User Defined Type. Basics of Structures. struct structure tag { variable declarations }; struct is a reserved word indicating the beginning of the structure definition structure tag is the name of the structure type and use to declare structure variables.

Download Presentation

Structure and User Defined Type

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Structure and User Defined Type

  2. Basics of Structures struct structure tag { variable declarations }; structis a reserved word indicating the beginning of the structure definition structure tag is the name of the structure type and use to declare structure variables. Variable declarations are set of data type declarations that make up the structure.

  3. Example struct employee { char name [40]; /* an array member */ int code; /* an int type member */ float salary; /* a float type member */ }; Notes : Don’t forget to put ; (semicolon) at the end of the structure type declaration or member declaration

  4. Declaring a structure type struct date {int day, month, year;}; *will creates a template for a structure call date that has three int type members NOTES • declaring a structure is declaring a new data type whose format is defined by the programmer • declaration statement creates a template for the specified structure type, but does not reserve space for it.

  5. Declaring Structure Variables struct tag variable-name; Example : struct employee agent1; * declares a variable called agents1 of type struct employee.

  6. Combine declaration and declare structure struct date { int day, month, year; } arrival_date, departure_date; or without tag structure { int day, month, year;} arrival_date, departure_date;

  7. Structure Initialization struct employee agent1 = { “Ahmas Ali”, 009, 10000.00 }; struct date arrival_date = { 1, 1, 2001}

  8. Structure Initialization struct employee agent1 = { “Ahmas Ali”, 009, 10000.00 }; struct date arrival_date = { 1, 1, 2001}

  9. Structure Initialization struct date { int day, month, year; } arrival_date = {1, 1, 2002}, departure_date={1, 12, 2002} struct date arrival_date = { 1, 1} is same as struct date arrival_date = {1, 1, 0}

  10. Accessing Structure Members Syntax structure.variable.member-name Example struct {char name[40]; int code; float salary;} agent1; agent1.name agent1.code agent1.salary

  11. Example /* declare a structure variable */ struct {int month, int day, int year;} Picasso; Picasso.day =25; /* assign 25 to member variable day */ Picasso.month = 10; /* assign 10 to member variable month */ Picasso.year=1881; /*assign 1881 to member variable year */

  12. Program Example Part 1/2 /* This program shows the structure declaration, initialization, accessing members, and structure assignments.*/ # include <stdio.h> /* including the stdio library */ int main ( ) { /* declaring a structure type (template) */ struct car { char maker [40] , model [40] ; int year ; } ; /* declaring a structure variable, and initializing it */ struct car FirstCar = { "Ford", "Mustang", 1996} ; /* declaring a structure variable */ struct car SecondCar ;

  13. Program Example Part 2/2 /* displaying the structure FirstCar */ printf ( "%20s %s, %s, %d\n", "First Car: ", FirstCar.maker, FirstCar.model, FirstCar. year) ; /* assigning FirstCar to SecondCar using the assignment operator */ SecondCar = FirstCar ; /* displaying the structure SecondCar */ printf ( "%20s %s, %s, %d\n", "Second Car: ", SecondCar.maker, SecondCar.model, SecondCar. year ) ; /* displaying the size of each structure variable */ printf ( "%20s is %d Bytes\n", "Size of FirstCar: ", sizeof ( FirstCar ) ) ; printf ( "%20s is %d Bytes\n", "Size of SecondCar: ", sizeof ( SecondCar ) ) ; return 0 ; }

  14. Structures And Pointers struct date Picasso = {25, 10, 1881}, * Pointer_to_Picasso /* declares structure variable Picasso, and a pointer variable of type struct date called Pointer_to_Picasso */ • use the address operator & to obtain the address of a structure Pointer_to_Picasso = &Picasso • use the pointer variable Pointer_to_Picasso to access the member variables of Picasso (*Pointer_to_Picasso).day /*parentheses are necessary because the precedence of .(dot) operator is higher than * */ * (Pointer_to_Picasso.day) /* is an error */

  15. Common Errors • Forgetting the * (indirection operator) when using a pointer variable with the . Dot operator • Forgetting the ( ) or placing them in the wrong place when using a pointer variable with the . (dot) operator

  16. The Arrow Operator : -> • C provides a special pointer operator -> called arrow operator, or structure pointer operator. • Can be used instead of the . (dot operator) to access the structure

  17. Different Methods of Accessing Structure Member struct date {int day, month, year}; Picasso = {25, 10, 1881}, * pointer; pointer=&Picasso ; Direct Access Arrow Pointer Member Notation Notation Notation Value Picasso.day Pointer->day (*pointer).day 25 Picasso.month Pointer->month (*pointer).month 10 Picasso.year Pointer->year (*pointer).year 10

  18. Structures and Functions • A structure variable can be passed as an argument to a function

  19. Example Part 1/4 /* This is an interactive program. It shows different ways of ordpassing structures to a function. */ # include <stdio.h> /* including the stdio library */ /* declaring a structure type */ struct car { char maker [40] , model [40] ; int year ; } ; int main ( ) { /* declaring a structure variable */ struct car FirstCar ; /* declaring functions */ void input ( struct car * ) ; void output ( char *, char *, int * ) ;

  20. Example Part 2/4 /* function calls */ /* passing the structure address */ input ( &FirstCar ) ; /* passing the addresses of the structure member variables */ output ( FirstCar.maker, FirstCar.model, &FirstCar.year ) ; return 0 ; }

  21. Example Part 3/4 /* input: This function expects a pointer to a structure of type struct car. It reads data items from the keyboard and saves them in the structure member variables. */ void input ( struct car * sp ) { puts ( "*** Car Information System ***" ) ; /* title message */ printf ( "What is the maker of your car? " ) ; /* prompt */ gets ( sp -> maker ) ; /* read */ printf ( "What is the model of your car? " ) ; /* prompt */ gets ( sp -> model ) ; /* read */ printf ( "What year is your car? " ) ; /* prompt */ scanf ( "%d", &sp -> year ) ; /* read */ return ; }

  22. Example Part 4/4 /* output: This function expects pointers to two strings and a pointer to an int typevariable. It displays the specified two strings and the integer number. */ void output ( char * s1, char * s2, int * ip ) { printf ( "Your Car: %s, %s, %d\n", s1, s2, * ip ) ; puts ("Nice Car!" ) ; return ; }

  23. Nested Structures struct plus { char color[10]; float price;}; struct car { char maker[40]; char model[40]; int year; struct plus more; /* member variable is a }; structure by itself */

  24. Initializing a Nested Structure struct car FirstCar = { “Ford”, “Proton”, 1997, {“Red”, 10000.00} }; Assessing Nested Structure • FirstCar.maker • FirstCar.more.color

  25. Example /* This program shows the structure declaration, initialization, accessing member variables, using a nested structure. */ # include <stdio.h> /* including the stdio library */ int main ( ) { /* declaring a structure type */ struct plus { char color [10] ; float price ; } ; struct car { char maker [40] , model [40] ; int year ; struct plus more ; /* the member variable is a structure by itself */ } ; /* declaring a structure variable, and initializing it */ struct car FirstCar = { "Ford", "Mustang", 1996, { "Red", 27000.00} }; /* display the structure FirstCar */ printf ( "First Car: %s, %s, %d, %s, $%.2f\n", FirstCar.maker, FirstCar.model, FirstCar. year, FirstCar.more.color, FirstCar.more.price ) ; return 0 ; }

  26. Array of Structures • struct car {char maker[40]; char model[40]; int year; }; • struct car CarInfo[100];

  27. Accessing Members of Structure Array struct car CarInfo[100]; notation CarInfo[0].name is accessing the structure member called name of the array’s first element

  28. Accessing Member of a Structure Array Using Pointer struct {char maker[40]; char model[40]; int year; } CarInfo[10], *sp sp = CarInfo; /* initialize the pointer to the array address */ sp[0].maker /* member variable maker in the array’s 1st element*/ sp[1].maker /* member variable maker in the array’s 2nd element*/

  29. Using typedef • typdef unsigned short US; • US X, array[10]; • tydedef char *SP; • SP *ptr1, *ptr2; same as char *ptr1, *ptr2;

  30. UNIONS • A union is a complex user-defined data type that provides storage for different data types in the same memory space • Unions are set up in the same way as structures are • Example union mixed { int Iplace; /* int storage */ float Fplace; /*float storage */ char Cplace; /*character storage */ };

  31. Enumerated Types Allow us to defined symbolic names to represent integer constants. Using enumerated type enchances the program readability Examples enum colors {red, blue, green, yellow}; enum colors MyColor;

  32. File Processing

  33. Files • The reading and writing operations are performed on disk-based entities called files • There are 2 modes of C Streams • text stream • is a sequence of characters organized into lines, each line consisting of up to 254 characters, and is terminated by a newline character • binary stream • is a sequence of unprocessed bytes. In this form, bytes are not translated in any special way, and are read and written exactly as they arre

  34. Operating System File information C Program open file statement Disk Pointer to the file structure File Operations • Opening a File • must open the file for use before any other file operations • File Pointer • A file pointer is a pointer to information that defines various characteristics of an opened file - information such as filename, current size, current status, & etc

  35. Opening A File • File pointer • FILE * fptr; /* declaring a file pointer variable */ • File position indicator • when a file is opened for read or write operations, the system creates a long int variable that is initialized to 0. • The value in this variable determines the location in the file that the program reads from or writes to.

  36. Opening a File : fopen( ) FILE *fptr; fptr = fopen(“test.txt”,”w”); declare a file pointer fptr, and the fopen( ) function opens a stream for use and associates test.txt with that stream

  37. File Modes Mode Meaning r open a text file for reading. The file must already exist w open a text file for writing. If the file exist, its contents will be written over. If doesn’t exist, one will be created. a open a text file for appending. Data will be added to the end of an existing file. If doesn’t exist, one will be created. r+ open a text file for both reading and writing. The file must already exist

  38. File Modes Mode Meaning w+ open a text file for both reading and writing. If the file exists, its content will be written over. a+ open a text file both for reading and appending. If the file doesn’t exist, one will be created.

  39. Notes • The number of files that can be opened at any one time is at least eight • the file mode such as “w” is a string and not a character, thus the double quotation marks • the filename format depends format depends on the operating system and may or may not include the filename extension characters.

  40. Character Output: putc( ) • Can write character by character, a line at a time, or a block at a time • command putc(‘A’, fptr) • Example char ch = ‘A’; do { putc(ch, fptr); } while (ch++ !=‘Z’);

  41. Character Input: getc( ) • Ch = getc(fptr); • read a character from test.txt • Example do{ ch = getc(fptr); } while(ch != EOF);

  42. Closing a File : fclose( ) • When finish reading from or writing to a file then need to close the file • fclose(fptr);

  43. Data sent to disk file is stored • Contents of the buffer is sent to the file when : • file is closed • buffer is full • program is terminated C Program Buffer Disk Output Buffers in Action

  44. Clearing Buffers: fflush( ) • Flushes the buffered but unwritten output to the file specified by the file pointer wothout closing the file. • Example • fflush(fptr);

  45. Common Errors • Opening a file in the wrong mode, for example, opening an existing file for writing using “w” destroys the content of the opened file. • Indicating the file mode as a character instead of the required string format. Thus ‘w’ is wrong and “w” is correct. • Using the filename in place of the file pointer variable when accessing a file. The only standard library function that uses the filename is the fopen( ) function

  46. Program /* This program shows the file processing, open, write and close file operations.*/ # include <stdio.h> /* including the stdio library */ int main ( ) { FILE * fptr; /* declare a file pointer */ char ch ; puts ( "Enter what you want to save in the file." ) ; /* prompt message */ puts ( "End your input with a Return key." ) ; /* open the file for write */ fptr = fopen ( "text.txt", "w" );/* set the file pointer */ while ( (ch = getchar ( ) ) != '\n' ) putc (ch, fptr ) ; /* write ch to a file indicated by fptr */ fclose ( fptr ) ; /* close the file indicated by fptr */ puts ( "Your input string is saved in a file called text.txt" ) ; puts ( "End of my act! :-) " ) ; return 0 ; }

  47. Program /*This program shows the file processing, open, read and close file operations.*/ # include <stdio.h> /* including the stdio library */ int main ( ) { FILE * fptr ; /* declare a file pointer */ int ch ; puts ( "The contents of the file text.txt is: " ) ; /* title message */ /* open file for read */ fptr = fopen ( "text.txt", "r" ); /* open file, and set the pointer fptr */ while ( ( ch = getc ( fptr ) ) != EOF ) /* read until end of the file */ putchar ( ch ) ; /* display ch */ fclose ( fptr ) ; /* close the file indicated by fptr */ puts ( "\nEnd of my act! :-) \n" ) ; return 0 ; }

  48. Common Error • Any variable used to detect the EOF must be declared as an int variable, not a char variable. • If ch is declared as a char variable, the expression while ((ch=getc(file_pointer))! = EOF) produces an infinite loop

  49. Program Part 1/2 /*This program shows the file processing, open,write/ read and close file operations.*/ # include <stdio.h> /* including the stdio library */ # include <stdlib.h> /* for exit ( ) */ int main ( ) { FILE * fptr ; /* declare a file pointer */ int ch ; puts ( "Enter what you want to save in the file." ) ; /* prompt message */ puts ( "End your input with a Return key." ) ; /* open file for write and read, and check for the file error */ if ( ( fptr = fopen ( "text.txt", "w+" ) ) == NULL ) /* check for error */ { printf ( "Failed to open file: text.txt\n") ; /* error message */ exit ( 1 ) ; /* exit program */ }

  50. Program Part 2/2 while ( (ch = getchar ( ) ) != '\n' ) putc ( ch, fptr ) ; /* write ch to a file indicated by fptr */ rewind ( fptr ) ; /* reset the file to its beginning */ puts ( "The contents of the file text.txt is: " ) ; /* title message */ while ( ( ch = getc ( fptr ) ) != EOF ) putchar ( ch ) ; /* display ch */ fclose ( fptr ) ; /* close the file indicated by fptr */ return 0 ; }

More Related