Structures in C Outline n Introduction n Structure

  • Slides: 44
Download presentation
Structures in C

Structures in C

Outline n Introduction n Structure Definitions n Initializing Structures n Accessing Members of Structures

Outline n Introduction n Structure Definitions n Initializing Structures n Accessing Members of Structures n Using Structures with Functions n typedef

Introduction n Limitation of simple primitive data types n Advantages of array n Limitations

Introduction n Limitation of simple primitive data types n Advantages of array n Limitations of array n How data is organized in real world ? n Address book , library book information, student information, etc.

Structures n Collections of related variables (aggregates) under one name n Can contain variables

Structures n Collections of related variables (aggregates) under one name n Can contain variables of different data types Commonly used to define records to be stored in files n Combined with pointers, can create linked lists, stacks, queues, and trees n

Creation of structure variable n Definition structure n Declaration structure variable and memory allocation.

Creation of structure variable n Definition structure n Declaration structure variable and memory allocation.

Syntax Structure definition n struct <structure name> { structure element 1 ; structure element

Syntax Structure definition n struct <structure name> { structure element 1 ; structure element 2 ; structure element 3 ; . . . };

Structure Definitions n Example struct Student { char name [20]; char address [20]; int

Structure Definitions n Example struct Student { char name [20]; char address [20]; int rollno; char class[5]; char year[20]; }; struct introduces the definition for structure Student n Student is the structure name and is used to declare variables of the structure type n

Structure Definitions n struct information n A struct cannot contain an instance of itself

Structure Definitions n struct information n 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 n Instead creates a new data type used to declare structure variables n Declarations n Declared like other variables: Student one. Stud, Stud[66], *SPtr; n Can use a comma separated list: struct Student { char name [20]; char address [20]; }one. Stud, Stud[66], *SPtr;

Declaration of Struct variable n struct book { char name ; float price ;

Declaration of Struct variable n struct book { char name ; float price ; int pages ; } b 1, b 2, b 3 ; Strut { char name ; float price ; int pages ; } b 1, b 2, b 3 ; n struct book { char name ; float price ; int pages ; }; struct book b 1, b 2, b 3

Structure n Valid Operations n Assigning a structure to a structure of the same

Structure n Valid Operations n Assigning a structure to a structure of the same type n Taking the address (&) of a structure Accessing the members of a structure (. ) n Using the sizeof operator to determine the size of a structure n

Initializing Structures n Initialize lists n Example: Student S 1 = { “Ashish", “Pune“

Initializing Structures n Initialize lists n Example: Student S 1 = { “Ashish", “Pune“ 2543, “SEV”, ” 2012 -1013”}; struct book { char name[10] ; float price ; int pages ; }; struct book b 1 = { "Basic", 130. 00, 550 } ; struct book b 2 = { "Physics", 150. 80, 800 } ;

Assignment statements n n Example: Student S 2 = S 1; Could also declare

Assignment statements n n Example: Student S 2 = S 1; Could also declare and initialize three. Hearts as follows: Student S 2; S 2. name = “Ashish”; S 2. address = “Pune”; S 2. rollno = 2543; S 2. class = “SEV”; s 2. year=“ 2012 -1013”;

Accessing Members of Structures n Accessing structure members n Dot operator (. ) used

Accessing Members of Structures n Accessing structure members n Dot operator (. ) used with structure variables Studnt S 1; printf( "%s", S 1. name ); n Arrow operator (->) used with pointers to structure variables Studnt *SPtr = &S 1; printf( "%s", SPtr->name ); n SPtr->name is equivalent to ( *SPtr ). name;

Memory allocation /* Memory map of structure elements */ main( ) { struct book

Memory allocation /* Memory map of structure elements */ main( ) { struct book { printf ( "n. Address of name = %u", &b 1. name ) printf ( "n. Address of price = %u", &b 1. price ) ; printf ( "n. Address of pages = %u", &b 1. pages ) ; } char name ; Here is the output of the program. . . float price ; Address of name = 65518 int pages ; Address of price = 65519 }; struct book b 1 = { 'B', 130. 00, 550 } ; Address of pages =65523

Array of Structures /* Usage of an array of structures */ main( ) {

Array of Structures /* Usage of an array of structures */ main( ) { struct book { char name ; float price ; int pages ; }; struct book b[100] ; int i ; for ( i = 0 ; i <= 99 ; i++ ) { printf ( "n. Enter name, price and pages " ) ; scanf ( "%c %f %d", &b[i]. name, &b[i]. price, &b[i]. pages ) ; } for ( i = 0 ; i <= 99 ; i++ ) printf ( "n%c %f %d", b[i]. name, b[i]. price, b[i]. pages ) ; }

Additional Features of Structures : 1. Structure and Assignment operator n The values of

Additional Features of Structures : 1. Structure and Assignment operator n The values of a structure variable can be assigned to another structure variable of the same type using the assignment operator. n No pease meal copy is needed. struct employee { char name[10] ; int age ; float salary ; };

Structure and Assignment operator struct employee e 1 = { "Sanjay", 30, 5500. 50

Structure and Assignment operator struct employee e 1 = { "Sanjay", 30, 5500. 50 } ; struct employee e 2, e 3 ; /* piece-meal copying */ strcpy ( e 2. name, e 1. name ) ; e 2. age = e 1. age ; e 2. salary = e 1. salary ; /* copying all elements at one go */ e 3 = e 2 ; printf ( "n%s %d %f", e 1. name, e 1. age, e 1. salary ) ; printf ( "n%s %d %f", e 2. name, e 2. age, e 2. salary ) ; printf ( "n%s %d %f", e 3. name, e 3. age, e 3. salary ) ;

Features : 2. Nested structure { n One structure can be char phone[15] ;

Features : 2. Nested structure { n One structure can be char phone[15] ; nested within another char city[25] ; structure. Using this int pin ; facility complex data types can be created. } ; The following program struct emp shows nested { structures at work. char name[25] ; main( ) struct address a ; { }; struct address struct emp e = { "jeru", "531046", "nagpur", 10 };

Features : 2. Nested structure printf ( "nname = %s phone = %s", e.

Features : 2. Nested structure printf ( "nname = %s phone = %s", e. name, e. a. phone ) ; printf ( "ncity = %s pin = %d", e. a. city, e. a. pin ) ;

Features : 3. Structures With Functions n Passing structures to functions n Pass entire

Features : 3. Structures With Functions n Passing structures to functions n Pass entire structure n Or, pass individual members n Both pass call by value n To pass structures call-by-reference n Pass its address n Pass reference to it

Features : 3. Structures With Functions Call by values n Like an ordinary variable,

Features : 3. Structures With Functions Call by values n Like an ordinary variable, a structure variable can also be passed to a function. n Or whole structure can be passed to a function

3. Passing individual structure elements main( ) { struct book { char name[25] ;

3. Passing individual structure elements main( ) { struct book { char name[25] ; char author[25] ; int callno ; }; struct book b 1 = { "Let us C", "YPK", 101 } ; display ( b 1. name, b 1. author, b 1. callno ) ; } void display ( char *s, char *t, int n ) { printf ( "n %s %s %d", s, t, n ) ; } And here is the output. . . Let us C YPK 101

3. Passing entire structure variable at a time struct book { char name[25] ;

3. Passing entire structure variable at a time struct book { char name[25] ; char author[25] ; int callno ; }; main() { struct book b 1 = { "Let us C", "YPK", 101 } ; display ( b 1 ) ; } display ( struct book b ) { printf ( "n%s %s %d", b. name, b. author, b. callno ) ; } n output. . . Let us C YPK 101

Features : 4. Structure and pointer n The way we can have a pointer

Features : 4. Structure and pointer n The way we can have a pointer pointing to an int, or a pointer pointing to a char. n similarly we can have a pointer pointing to a struct. n Such pointers are known as ‘structure pointers’

Example : Structure and pointer Void main () struct book b 1 = {

Example : Structure and pointer Void main () struct book b 1 = { "Let us C", "YPK", 101 } ; { struct book *ptr ; struct book ptr = &b 1 ; { printf ( "n%s %s %d", b 1. name, b 1. author, char name[25] ; b 1. callno ) ; char author[25] ; printf ( "n%s %s %d", ptr->name, ptr>author, ptr->callno ) ; int callno ; };

Structure and pointer memory map

Structure and pointer memory map

Call by reference and structure /* Passing address of a structure variable */ struct

Call by reference and structure /* Passing address of a structure variable */ struct book { char name[25] ; char author[25] ; int callno ; }; void main() { struct book b 1 = { "Let us C", "YPK", 101 } ; display ( &b 1 ); } display ( struct book *b ) { printf ( "n%s %s %d", b-> name, b->author, b->callno ) ; } And here is the output. . . Let us C YPK 101

Array of structure and pointer struct book { char name[25] ; char author[25] ;

Array of structure and pointer struct book { char name[25] ; char author[25] ; int callno ; }; void main() { int n; struct book b 1[20] n= input (b 1) display ( b 1, n ); } void display(struct book *b , int n) { int I; printf(“ntt Books Available “ ); printf(“|nt Sr. No t Name t Aruthor t Call No nn“ ); for(i=0; i<n; i++) { pritnf(“ntt %d t %s t %d “, i, +1, *(b+i)->)name, *(b+i)-> author, *(b+i)->callno); } }

Input function int input(struct book *b ) int I , n; printf(“ntt Enter No

Input function int input(struct book *b ) int I , n; printf(“ntt Enter No of books “); scanf(“%d”, &n); for(i=0; i<n; i++) { printf(“|nt Sr. No %d “, i+1); printf(“nt Name : : : flushall(); gets(*(b+i) -> name); printf(“nt Author Name : : : flushall(); gets(*(b+i) -> author); printf(“nt Call No nn“ ); scanf(“ %d “, &(b+i)->calln 0); } return n; }

Uses of Structures n Data base management n Changing the size of the cursor

Uses of Structures n Data base management n Changing the size of the cursor n Clearing the contents of the screen n Placing the cursor at an appropriate position on screen n Drawing any graphics shape on the screen n Receiving a key from the keyboard n Checking the memory size of the computer n Finding out the list of equipment attached to the computer n Formatting a floppy n Hiding a file from the directory n Displaying the directory of a disk n Sending the output to printer n Interacting with the mouse

What would be the output of the following programs: main( ) { struct gospel

What would be the output of the following programs: main( ) { struct gospel { int num ; char mess 1[50] ; char mess 2[50] ; }m; m. num = 1 ; strcpy ( m. mess 1, "If all that you have is hammer" ) ; strcpy ( m. mess 2, "Everything looks like a nail" ) ; /* assume that the strucure is located at address 1004 */ printf ( "n%u %u %u", &m. num, m. mess 1, m. mess 2 ) ; }

What would be the output of the following programs struct gospel { int num

What would be the output of the following programs struct gospel { int num ; char mess 1[50] ; char mess 2[50] ; } m 1 = { 2, "If you are driven by success", "make sure that it is a quality drive“ } ; main( ) { struct gospel m 2, m 3 ; m 2 = m 1 ; m 3 = m 2 ; printf ( "n%d %s %s", m 1. num, m 2. mess 1, m 3. mess 2 ) ; }

Point out the errors, if any, in the following programs: main( ) { struct

Point out the errors, if any, in the following programs: main( ) { struct employee { char name[25] ; int age ; float bs ; }; struct employee e ; strcpy ( e. name, "Hacker" ) ; age = 25 ; printf ( "n%s %d", e. name, age ) ; }

Point out the errors, if any, in the following programs: main( ) { struct

Point out the errors, if any, in the following programs: main( ) { struct { char name[25] ; char language[10] ; }; struct employee e = { "Hacker", "C" } ; printf ( "n%s %d", e. name, e. language ) ; }

struct virus { char signature[25] ; char status[20] ; int size ; } v[2]

struct virus { char signature[25] ; char status[20] ; int size ; } v[2] = { "Yankee Doodle", "Deadly", 1813, "Dark Avenger", "Killer", 1795 } ; main( ) { int i ; for ( i = 0 ; i <=1 ; i++ ) printf ( "n%s %s", v. signature, v. status ) ; }

typedef n typedef Creates aliases for previously defined data types n Use typedef to

typedef n typedef Creates aliases for previously defined data types n Use typedef to create shorter type names n n Typedef allows us to associate a name with a structure (or other data type).

Typedef n Put typedef at the start of your program. typedef struct line {

Typedef n Put typedef at the start of your program. typedef struct line { int x 1, y 1; int x 2, y 2; } LINE; int main() { LINE line 1; } line 1 is now a structure of line type

Typedef Example typedef struct { char *first; char *last; char SSN[9]; float gpa; char

Typedef Example typedef struct { char *first; char *last; char SSN[9]; float gpa; char **classes; } student; student stud_a, stud[20] , *sptr;

struct employee { char name[25] ; int age ; float bs ; } typedef

struct employee { char name[25] ; int age ; float bs ; } typedef empoyee emp;

UNION n Like structures, but every member occupies the same region of memory! Structures:

UNION n Like structures, but every member occupies the same region of memory! Structures: members are “and”ed together: “name and species and owner” n Unions: members are “xor”ed together n union VALUE { float f; int i; char *s; };

Unions n Storage n size of union is the size of its largest member

Unions n Storage n size of union is the size of its largest member n avoid unions with widely varying member sizes; for the larger data types, consider using pointers instead n Initialization n Union may only be initialized to a value appropriate for the type of its first member 42

Memory allocation union techno { int comp_id; char nm; float sal; }tch; Accessing element

Memory allocation union techno { int comp_id; char nm; float sal; }tch; Accessing element : tch. comp_id tch. nm tch. sal

Usage n access individual bytes of larger type n variable format input records (coded

Usage n access individual bytes of larger type n variable format input records (coded records) n sharing an area to save storage usage n unions not used nearly as much as structures