Structures in C.

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Advertisements

Incomplete Structs struct B; struct A { struct B * partner; // other declarations… }; struct B { struct A * partner; // other declarations… };
1 Chapter 10 - Structures, Unions, Bit Manipulations, and Enumerations Outline 10.1Introduction 10.2Structure Definitions 10.3Initializing Structures 10.4Accessing.
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.
Computer Programming for Engineering Applications ECE 175 Intro to Programming.
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.
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.
Programming in C Chapter 10 Structures and Unions
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
Structures Often we want to be able to manipulate logical entities as a whole For example, complex numbers, dates, student records, etc Each of these must.
C Language.
C Structures and Memory Allocation There is no class in C, but we may still want non- homogenous structures –So, we use the struct construct struct for.
C Structures Basics of structures Typedef. Data Hierarchy Byte –8 bits (ASCII character ‘A’ = ) Field –Group of characters (character string “Fred”)
Structure.
Programming Paradigms Introduction. 6/15/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved. L1:
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 Spring 2013Programming and Data Structure1.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
CSC141- Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 25 Thanks for Lecture Slides: Dr. Sadaf Tanveer Dr. Sadaf Tanveer,
1 C++ Syntax and Semantics The Development Process.
Structures. An array allows us to store a collection of variables However, the variables must be of the same type to be stored in an array E.g. if we.
Software Development Method. Assignments Due – Homework 0, Warmup Reading – Chapter 2 –
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 10 - C Structures, Unions, Bit Manipulations,
1 Key Concepts:  Data types in C.  What is a variable?  Variable Declaration  Variable Initialization  Printf()  Scanf()  Working with numbers in.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 10 - Structures, Unions, Bit Manipulations, and Enumerations Outline 10.1Introduction 10.2Structure.
Programming C/C++ on Eclipe Trình bày : Ths HungNM C/C++ Training.
Guide To UNIX Using Linux Third Edition
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
Lecture No: 16. The scanf() function In C programming language, the scanf() function is used to read information from standard input device (keyboard).
'C' Programming With Structure Records Purpose of structures Coding a structure template Defining a new data type Functions which communicate using structures.
Functions, Pointers, Structures Keerthi Nelaturu.
Introduction to Data Structures Systems Programming.
1 Pointers and Arrays. 2 When an array is declared,  The compiler allocates sufficient amount of storage to contain all the elements of the array in.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 10 - C Structures, Unions, Bit Manipulations,
1 Structures UniMAP SEM I - 11/12EKT 120 Computer Programming.
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.
PHYS 2020 Basic C An introduction to writing simple but useful programs in C In these lectures I will take you through the basics of C, but you will need.
Spring 2005, Gülcihan Özdemir Dağ Lecture 11, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 11 Outline 11.1.
 2007 Pearson Education, Inc. All rights reserved C Structures, Unions, Bit Manipulations and Enumerations.
Introduction to Data Structures Systems Programming Concepts.
 Structures are like arrays except that they allow many variables of different types grouped together under the same name. For example you can create.
Chapter 13: Structures. In this chapter you will learn about: – Single structures – Arrays of structures – Structures as function arguments – Linked lists.
Pointers. Pointer Variable Declarations and Initialization Pointer variables – Contain memory addresses as their values – Normal variables contain a specific.
Welcome to Concepts of Pointers. Prepared by:- Sumit Kumar PGT(Computer Science) Kv,Samba.
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 CSC103: Introduction to Computer and Programming Lecture No 24.
1 EPSII 59:006 Spring HW’s and Solutions on WebCT.
Structures. Outline Introduction Structure Definitions and declarations Initializing Structures Operations on Structures members Structures as Functions.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI N305 Structures Declarations.
1. 2 Introduction Structure Definitions and Declarations Initializing Structures Operations on Structures Members Structures as Functions Parameters Array.
Introduction to Computers and Programming Class 24 Structures (structs) Professor Avi Rosenfeld.
 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.
STRUCTURES. INTRODUCTION A structure is same as that of records. It stores related information about an entity. Structure is basically a user defined.
13/10/2016CS150 Introduction to Computer Science 1 Multidimensional Arrays  Arrays can have more than one column  Two dimensional arrays have two columns.
Lecture 10: Structures. Outline Introduction Structure Definitions and declarations Initializing Structures Operations on Structures members Structures.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI
Structure, Unions, typedef and enumeration
C Structures, Unions, Bit Manipulations and Enumerations
Visit for more Learning Resources
Introduction to Data Structures
Buy book Online -
C Structures, Unions, and Enumerations
C Structures, Unions, Bit Manipulations and Enumerations
Structure.
Structures Declarations CSCI 230
Presentation transcript:

Structures in C

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

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

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

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

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

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

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

Declaration of Struct variable struct book { char name ; float price ; int pages ; } b1, b2, b3 ; Strut struct book { char name ; float price ; int pages ; } ; struct book b1, b2, b3

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

Initializing Structures Initialize lists Example: Student S1 = { “Ashish", “Pune“ 2543, “SEV”, ”2012-1013”}; struct book { char name[10] ; float price ; int pages ; } ; struct book b1 = { "Basic", 130.00, 550 } ; struct book b2 = { "Physics", 150.80, 800 } ;

Assignment statements Example: Student S2 = S1; Could also declare and initialize threeHearts as follows: Student S2; S2.name = “Ashish”; S2.address = “Pune”; S2.rollno = 2543; S2.class = “SEV”; s2.year=“ 2012-1013”;

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

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

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 ( "\nEnter name, price and pages " ) ; scanf ( "%c %f %d", &b[i].name, &b[i].price, &b[i].pages ) ; } printf ( "\n%c %f %d", b[i].name, b[i].price, b[i].pages ) ;

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

Structure and Assignment operator struct employee e1 = { "Sanjay", 30, 5500.50 } ; struct employee e2, e3 ; /* piece-meal copying */ strcpy ( e2.name, e1.name ) ; e2.age = e1.age ; e2.salary = e1.salary ; /* copying all elements at one go */ e3 = e2 ; printf ( "\n%s %d %f", e1.name, e1.age, e1.salary ) ; printf ( "\n%s %d %f", e2.name, e2.age, e2.salary ) ; printf ( "\n%s %d %f", e3.name, e3.age, e3.salary ) ;

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

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 Passing structures to functions Pass entire structure Or, pass individual members Both pass call by value To pass structures call-by-reference Pass its address Pass reference to it

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

3. Passing individual structure elements main( ) { struct book char name[25] ; char author[25] ; int callno ; } ; struct book b1 = { "Let us C", "YPK", 101 } ; display ( b1.name, b1.author, b1.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] ; char author[25] ; int callno ; } ; main() struct book b1 = { "Let us C", "YPK", 101 } ; display ( b1 ) ; } display ( struct book b ) { printf ( "\n%s %s %d", b.name, b.author, b.callno ) ; } output... Let us C YPK 101

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

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

Structure and pointer memory map

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 b1 = { "Let us C", "YPK", 101 } ; display ( &b1 ); } 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] ; int callno ; } ; void main() { int n; struct book b1[20] n= input (b1) display ( b1,n ); } void display(struct book *b , int n) { int I; printf(“\n\t\t Books Available “ ); printf(“|n\t Sr. No \t Name \t Aruthor \t Call No \n\n“ ); for(i=0;i<n;i++) { pritnf(“\n\t\t %d \t %s \t%s \t %d “,i,+1, *(b+i)->)name, *(b+i)-> author,*(b+i)->callno); }

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

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

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

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

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 { 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] = { "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 typedef Creates aliases for previously defined data types Use typedef to create shorter type names Typedef allows us to associate a name with a structure (or other data type).

Typedef Put typedef at the start of your program. typedef struct line { int x1, y1; int x2, y2; } LINE; int main() { LINE line1; } line1 is now a structure of line type

Typedef Example typedef struct { } student; 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 empoyee emp;

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

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

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

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