UNIT - V STRUCTURES AND UNIONS

Similar documents
Unit 8. Structures and Unions. School of Science and Technology INTRODUCTION

Darshan Institute of Engineering & Technology for Diploma Studies Unit 5

Structure, Union. Ashishprajapati29.wordpress.com. 1 What is structure? How to declare a Structure? Explain with Example

School of Science and Technology

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

Subject: Fundamental of Computer Programming 2068

Computer Programming Unit 3

Example: Structure, Union. Syntax. of Structure: struct book { char title[100]; char author[50] ]; float price; }; void main( )

IV Unit Second Part STRUCTURES

First of all, it is a variable, just like other variables you studied

Unit IV & V Previous Papers 1 mark Answers

MCA Semester 1. MC0061 Computer Programming C Language 4 Credits Assignment: Set 1 (40 Marks)

Chapter-14 STRUCTURES

DECLARAING AND INITIALIZING POINTERS

A3-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH 'C' LANGUAGE

Structures in C. Rab Nawaz Jadoon DCS. Assistant Professor. Department of Computer Science. COMSATS IIT, Abbottabad Pakistan

INTRODUCTION 1 AND REVIEW

AMCAT Automata Coding Sample Questions And Answers

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Pointers and Arrays 1

UNIT-V. Structures. The general syntax of structure is given below: Struct <tagname> { datatype membername1; datatype membername2; };

Dynamic Memory Allocation

Unit 3 Decision making, Looping and Arrays

3.3 Structures. Department of CSE

Data Types and Variables in C language

Multi-Dimensional arrays

Language comparison. C has pointers. Java has references. C++ has pointers and references

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100

DC54 DATA STRUCTURES DEC 2014

The syntax of structure declaration is. struct structure_name { type element 1; type element 2; type element n;

Write a C program using arrays and structure

Arrays in C. Rab Nawaz Jadoon DCS. Assistant Professor. Department of Computer Science. COMSATS IIT, Abbottabad Pakistan

Pointer in C SHARDA UNIVERSITY. Presented By: Pushpendra K. Rajput Assistant Professor

POINTERS, STRUCTURES AND INTRODUCTION TO DATA STRUCTURES

M4.1-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

M3-R4: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

F.Y. Diploma : Sem. II [CO/CD/CM/CW/IF] Programming in C

Government Polytechnic Muzaffarpur.

Prepared by: Shraddha Modi

Worksheet 4 Basic Input functions and Mathematical Operators

3/22/2016. Pointer Basics. What is a pointer? C Language III. CMSC 313 Sections 01, 02. pointer = memory address + type

Engineering program development 6. Edited by Péter Vass

10/20/2015. Midterm Topic Review. Pointer Basics. C Language III. CMSC 313 Sections 01, 02. Adapted from Richard Chang, CMSC 313 Spring 2013

Solution Set(Reference Book - Programming with c By Byron Gottfried Thrid Edition)

CS2351 Data Structures. Lecture 7: A Brief Review of Pointers in C

UNIT-IV. Structure is a user-defined data type in C language which allows us to combine data of different types together.

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Downloaded S. from Kiran, PGT (CS) KV, Malleswaram STRUCTURES. Downloaded from

b. array s first element address c. base address of an array d. all elements of an array e. both b and c 9. An array elements are always stored in a.

UNDERSTANDING THE COMPUTER S MEMORY

CS113: Lecture 5. Topics: Pointers. Pointers and Activation Records

by: Lizawati, Norhidayah & Muhammad Noorazlan Shah Computer Engineering, FKEKK, UTeM

Arrays. Example: Run the below program, it will crash in Windows (TurboC Compiler)

Variation of Pointers

UNIT 3 FUNCTIONS AND ARRAYS

Scheme G. Sample Test Paper-I. Course Name : Computer Engineering Group Course Code : CO/CD/CM/CW/IF Semester : Second Subject Tile : Programming in C

Arrays in C. By Mrs. Manisha Kuveskar.

Creating a C++ Program

Object Oriented Pragramming (22316)

C PROGRAMMING Lecture 4. 1st semester

Chapter-8 DATA TYPES. Introduction. Variable:

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

ESC101N Fundamentals of Computing

COP 3223 Introduction to Programming with C - Study Union - Spring 2018

Pointers. Introduction

Parameter passing. Programming in C. Important. Parameter passing... C implements call-by-value parameter passing. UVic SEng 265

Basics of Programming

Lecture 16 Introduction To Structures

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, SPRING 2013

Pointers. A pointer value is the address of the first byte of the pointed object in the memory. A pointer does not know how many bytes it points to.

Procedures, Parameters, Values and Variables. Steven R. Bagley

Questions Bank. 14) State any four advantages of using flow-chart

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

Darshan Institute of Engineering & Technology for Diploma studies Unit 4

Fundamental of Programming (C)

Solution: A pointer is a variable that holds the address of another object (data item) rather than a value.

Basic Elements of C. Staff Incharge: S.Sasirekha

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

AE52/AC52/AT52 C & Data Structures JUNE 2014

MYcsvtu Notes LECTURE 34. POINTERS

M1-R4: Programing and Problem Solving using C (JAN 2019)

Problem Solving and 'C' Programming

Lab 3. Pointers Programming Lab (Using C) XU Silei

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

'C' Programming Language

C library = Header files + Reserved words + main method

Module 6: Array in C

An array is a collection of similar elements that is all the elements in an array should have same data type. This means that an array can store

Chapter 1 & 2 Introduction to C Language

PROGRAMMAZIONE I A.A. 2017/2018

Two Dimensional Arrays

C: How to Program. Week /Mar/05

A First Book of ANSI C Fourth Edition. Chapter 8 Arrays

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

Transcription:

UNIT - V STRUCTURES AND UNIONS

STRUCTURE DEFINITION A structure definition creates a format that may be used to declare structure variables. Let us use an example to illustrate the process of structure definition and the creation of structure variables. Consider a book database consisting of book name, author, number of pages, and price. We can define a structure to hold this information as follows: struct book_bank char title[20]; char author[15]; int pages; float price; };

STRUCTURE DEFINITION The keyword struct declares a structure to hold the details of four fields, namely title, author, pages and price. These fields are called structure elements or members. Each member may belong to a different type of data. book_bank is the name of the structure and is called the structure tag. The tag name may be used subsequently to declare variables that have the tag s structure. The above declaration has not declared any variables. It simply describes a format called template to represent information as shown below.

title array of 20 characters author array of 15 characters pages integer price float The general format of a structure definition is as follows: struct tag_name data_type member1; data_type member2; data_type member3; };

We can declare structure variables using the tag name anywhere in the program. For example, the statement struct book_bank book1, book2, book3; declares book1, book2, and book3 as variables of type struct book_bank. Remember that the members of a structure themselves are not variables. They do not occupy any member until they are associated with the structure variable such as book1.

In defining a structure you may note the following syntax: 1. The template is terminated with a semicolon. 2. While the entire declaration is considered as a statement, each member is declared independently for its name and type in a separate statement inside the template. 3. The tag_name such as book_bank can be used to declare structure variables of its type, later in the program.

struct personal char name[20]; int day; char month[10]; int year; float salary; }; main() struct personal person; printf( input values\n ); scanf( %s %d %s %d %f, person.name, &person.day, person.month, &person.year, &person.salary); printf( %s %d %s %d %f\n, person.name, person.day, person.month, person.year, person.salary); } /* Defining and accessing structure members */

STRUCTURE DEFINITION Like any other data type, a structure variable can be initialized. However, a structure must be declared as static if it is to be initialized inside a function. E.g main() static struct } int weight; float height; student=60,180.75};.......... } This is not applicable to ANSI compilers. The keyword static would enable us to run them under both the old and ANSI standard compilers. This assigns the value 60 to student.weight and 180.75 to student.height.

A lot of variation is possible in initializing a structure. The following statement initialize two structure variables. Here it is essential to use a tag name. main() struct st_record int weight; float height; }; static struct st_record student1=60,180.75}; static struct st_record student2=53,170.60};..... } Another method is to initialize a structure variable outside the function as shown below: struct st_record /* no static word */ int weight; float height; }student1=60,180.75}; main() static struct st_record student 2=53,170.60};.... }

Comparison of structure variables Two variables of the same structure type can be compared the same way as ordinary variables. If person1 and person2 belong to the same structure, then the following operations are valid: operations Person1=person2 Person1==person2 Person1!=person2 Meaning Assign person2 to person1 Compare all members of person1 and person2 and return 1 if they are equal, 0 otherwise Return 1 if all the members are not equal, 0 otherwise

/* COMPARISON OF STRUCTURE VARIABLES */ struct class int number; char name[20]; float marks; }; main() int x; static struct class student1=111, Rao,72.50}; static struct class student2=222, Reddy,67.00}; struct class student3; student3=student2; x = ( (student3.number = = student2.number) && (student3.marks = = student2.marks) )? 1 : 0; if (x = = 1) printf( \n student2 and student3 are same \n\n ); printf( %d %s %f \n, student3.number, student3.name, student3.marks); } else printf( \n student2 and student3 are different\n\n ); }

Arrays of structure we may use a template to describe student name and marks obtained in various subjects and then declare all the student as structure variables. In such cases, we may declare an array of structures, each element of the array representing a structure variable. For e.g. struct class student[100]; defines an array student, that consists of 100 elements. Each element is defined to be of the type struct class.

Arrays of structure Consider the following declarations: struct marks int subject1; int subject2; int subject3; }; main() static struct marks student[3]= 45,68,81}, 75,53,69}, 57,40,71} };...... } This declares the student as an array of three elements student1, student2, student3 and initializes as follows: student[0].subject1=45; student[0].subject2=68;.... student[2].subject3=71;

struct marks int sub1;int sub2; int sub3; int total; }; void main() int i; struct marks student[3]= 45,67,81,0}, 75,53,69,0}, 57,36,71,0} }; static struct marks total; for(i=0;i<=2;i++) student[i]total=student[i].sub1+student[i].sub2+student[i].sub3; total.sub1=total.sub1+student[i].sub1; total.sub2=total.sub2+student[i].sub2; total.sub3=total.sub3+student[i].sub3; total.total=total.total+student[i].total; } printf( STUDENT TOTAL\n\n ); for(i=0;i<=2;i++) printf( Student[%d] %d\n,i+1,student[i].total); printf( SUBJECT TOTAL\n\n ); printf( %s %d\n%s %d\n%s %d\n, Subject1,total.sub1, Subject2,total.sub2, Subject3,total.sub3); printf( \n Grand Total = %d\n, total.total); }

Union In structures, each member has its own storage location, whereas all the members of a union use the same location. This implies that, although a union may contain many members of different types, it can handle only one member at a time. Syntax: union item int m; float x; char c; }code;

The union contains three members, each with a different data type. However, we can use only one of them at time. This is due to the fact that only one location is allocated for a union variable, irrespective of its size. 1000 1001 1002 1003 Storage of 4 bytes c m x

POINTERS Pointers are another important feature of C language, they are a powerful tool and handy to use once they are mastered. There are number of reasons for using pointers. 1. A pointer enables us to access a variable that is defined outside the function. 2. Pointers reduces the length and complexity of a program. 3. They increase the execution speed. 4. The use of a pointer array to character string results in saving of data storage space in memory.

Consider the following statement: int quantity = 179; This statement instructs the system to find a location for the integer variable quantity and puts the value 179 in that location. Let us assume that the system has chosen the address location 5000 for quantity. We may represent this as shown below. quantity Variable 179 value 5000 Address

During execution of the program, the system always associates the name quantity with the address 5000. We may have access to the value 179 by using either the name quantity or the address 5000. since memory addresses are simply numbers, they can be assigned to some variables which can be stored in memory, like another variables. Such variables that hold memory addresses are called pointers. A pointer is, therefore, nothing but a variable that contains an address which is a location of another variable in memory.

Variable quantity value 179 Address 5000 p 5000 5048 Since the value of variable P is the address of the variable quantity, we may access the value of quantity by using the value of p and therefore, we say that the variable p points to the variable quantity. Thus, gets the name pointer.

Declaring and initializing pointers The declaration of a pointer variable takes the following form: datatype *pt_name; This tells the compiler three things about the variable pt_name. 1. The asterisk (*) tells that the variable pt_name is a pointer variable. 2. pt_name needs a memory location. 3. pt_name points to a variable of type data type. For example: int *p; Declares the variable p as a pointer variable that points to an integer data type.

stage Values in the storage cells and their addresses x y ptr Declaration 4104 4108 4106 - address x = 10 10 4104 4108 4106 - address ptr = &x 10 4104 4104 4108 4106 - address y = *ptr *ptr = 25 10 10 4104 4104 4108 4106 -------- pointer to x 25 10 4104 - address 4104 4108 4106

Pointer Expression Like other variables, pointer variables can be used in expressions. For example if p1 and p2 are properly declared and initialized pointers, then the following statements are valid: y = *p1 * *p2; sum = sum + *p1; z = 5 * - *p2 / *p1; *p2 = *p2 + 10; same as (*p1) * (*p2) same as ( 5 * (-(*p2))) / (*p1) Note that there is a blank space between / and * in the item 3 above. The following is invalid z = 5* - *p2/*p1; The symbol /* is considered as the beginning of a comment and therefore the statement fails.

/* ILLSTARTION OF POINTER EXPRESSION */ #include<stdio.h> #include<conio.h> void main() int a,b,*p1,*p2,x,y,z; clrscr(); a=12; b=4; p1=&a; p2=&b; x=*p1 * *p2-6; y=4 * - *p2 / *p1 + 10; printf("address of a = %u\n",p1); printf("address of b = %u\n",p2); printf("\n"); printf("a = %d B = %d\n",a,b); printf("x = %d y = %d\n",x,y); *p2 = *p2 + 3; *p1 = *p2-5; z = *p1 * *p2-6; printf("\na = %d, b = %d,",a,b); printf(" z = %d\n", z); getch(); }

Pointers and Arrays When an array is declared, the compiler allocates a base address and sufficient amount of storage to contain all the elements of the array in contiguous memory locations. The base address is the location of the first element (index 0) of the array. The compiler also defines the array name as a constant pointer to the first element. Suppose we declare an array x as follows: static int x[5] = 1,2,3,4,5};

Pointers and Arrays Suppose the base address of x is 1000 and assuming that each integer requires two bytes, the five elements will be stored as follows: Element -- Value -- X[0] X[1] X[2] X[3] X[4] 1 2 3 4 5 Address -- 1000 1002 1004 1006 1008 Base Address The name x is defined as constant pointer pointing to the first element, x[0] and therefore the value of x is 1000, the location where x[0] is stored. That is,

x = &x[0]; If we declare p as an integer pointer, then we can make the pointer p to point to the array x by the following assignment: p = x; This is equivalent to p = &x[0]; Now, we can access every value of x using p++ to move from one element to another. The relationship between p and x is shown below: p = &x[0] (= 1000) p+1 = &x[1] (= 1002) p+2 = &x[2] (= 1004) p+3 = &x[3] (= 1006) p+4 = &x[4] (= 1008) Address of x[3] = base address + (3 * scale factor of int) = 1000 + (3 * 2) = 1006

/* pointers in one dimensional Arrays */ void main() int *p, sum, i; static int x[5]=5,9,6,3,7}; i = 0; p = x; printf( Element Value Address\n\n ); while(i<5) printf( x[%d] %d %u\n, i, *p, p); sum=sum + *p; i++; p++; } printf( \n Sum = %d \n,sum); printf( \n &x[0]= %u\n,&x[0]); printf( \n p } = %u\n, p);