Sudeshna Sarkar 7th March 2017 Structures Sudeshna Sarkar 7th March 2017
Structure Combine heterogeneous data to form a named collection
Structures: basics ideas Structure = collection of variables Members of a structure: variables in the collection Structure = super variable, denotes the memory used for all members. Each structure has a name, the name refers to the super variable, i.e. entire collection. Each structure has a type: the type defines what variables there will be in the collection.
Structure types You can define a structure type for each type of entity that you want to represent on the computer. “Programmer defined type” Example: To represent books, you can define a Book structure type. When you define a structure type, you must say what variables each structure of that type will contain. Example: In a structure to represent books, you may wish to have variables to store the name of the book, its price, …
Defining a structure type General form struct structure-type{ member1-type member1-name; member2-type member2-name; … }; // Don’t forget the semicolon! Example struct Book{ char title[50]; double price; }; A structure-type is a user-defined data type, just as int, char, double are primitive data types. Structure-type name and member names can be any identifiers.
Defines a new type E.g., Name of the type struct motor { float volts; float amps; int phases; float rpm; }; //struct motor Name of the type Note: name of type is optional if you are just declaring a single struct
struct Defines a new type E.g., struct motor { float volts; float amps; int phases; float rpm; }; //struct motor Members of the struct
Declaring struct variables struct motor p, q, r; Declares and sets aside storage for three variables , p, q, and r, each of type struct motor struct motor M[25]; Declares a 25-element array of struct motor; allocates 25 units of storage, each one big enough to hold the data of one motor struct motor *m; Declares a pointer to an object of type struct motor
Example A structure definition: struct student { char name[30]; int roll_number; int total_marks; char dob[10]; }; Defining structure variables: struct student a1, a2, a3; A new data-type
Structures Compound data: A date is struct ADate { int month; int day; an int month and an int day and an int year struct ADate { int month; int day; int year; }; struct ADate date; date.month = 9; date.day = 1; date.year = 2005;
Structure Representation & Size struct CharCharInt { char c1; char c2; int i; } foo; foo.c1 = ’a’; foo.c2 = ’b’; foo.i = 0xDEADBEEF; sizeof(struct …) = sum of sizeof(field) + alignment padding Processor- and compiler-specific 62 61 EF BE AD DE c1 c2 i padding x86 uses “little-endian” representation
Members struct name { char first[10]; char midinit; char last[20]; } sname, ename; To access the members of a structure, we use the member access operator “.”. strcpy (sname.first, “Aritra”); sname.midinit = ‘K’; strcpy (sname.last, “Saha”) ;
Defining a structure The composition of a structure may be defined as: struct tag { member 1; member 2; : member m; }; } variable_1, variable_2,…, variable_n;
typedef a typedef is a way of renaming a type struct name { char first[10]; char midinit; char last[20]; } ; typedef struct name nameType; nameType name1, name2; typedef struct { char first[10]; char midinit; char last[20]; } NAMETYPE; NAMETYPE sname, ename;
Processing a Structure The members of a structure are processed individually, as separate entities. A structure member can be accessed by writing variable.member Examples: a1.name, a2.name, a1.roll_number, a3.dob
Operations on struct Copy/assign Get address Access members struct motor p, q; p = q; Get address struct motor p; struct motor *s s = &p; Access members p.volts; (*s).amps; s->amps;
Things you can and can't do Use = to assign whole struct variables Have a struct as a function return type You cannot Use == to directly compare struct variables; can compare fields directly Directly scanf or printf structs; can read fields one by one.
Operations on struct (function call) Passing an argument by value is an instance of copying or assignment Passing a return value from a function to the caller is an instance of copying or assignment struct motor f (struct motor g) { struct motor h = g; ...; return h; }
Struct initializers /* typedef structs go on top */ StudentRecord s1 = {"V Singhal", “17CS1002", 167, 8.31}; Using components of struct variables s1.height = 169; s1.cgpa = 8.4; scanf ("%s", s1.rollno) ;
Example: Complex number addition typedef struct { float real; float imaginary; } complex; int main( ) { complex a, b, c; scanf (“%f %f”, &a.real, &a.imaginary); scanf (“%f %f”, &b.real, &b.imaginary); c.real = a.real + b.real; c.imaginary = imaginary + b.imaginary; printf (“\n %f + %f j”, c.real, c.imaginary); }
Example: Complex number #include <stdio.h> typedef struct { float real; float imaginary; } complex; complex read_complex ( ) { complex c; scanf (“%f %f”, &c.real, &c.imaginary); return c; } void print_complex (complex c) { printf (“ %f + i %f ”, c.real, c.imaginary);
Complex number arithmetic complex add_complex (complex c1, complex c2) { complex csum; csum.real = c1.real + c2.real; csum.imaginary = c1.imaginary + c2.imaginary; return csum; } complex sub_complex (complex c1, complex c2) { complex cdiff; cdiff.real = c1.real + c2.real; cdiff.imaginary = c1.imaginary + c2.imaginary; return cdiff;
Complex number arithmetic complex mult_complex (complex c1, complex c2) { complex cprod; cprod.real = cprod.imaginary = return cprod; } int main ( ) { complex c1, c2, c3, c4; read_complex (c1) ; read_complex (c2) ; c3 = add_complex (c1, c2) ; printf (“Sum of”) ; print_complex (c1) ; printf (“and”); print_complex (c2); printf(“is”) ; print_complex (c3);
Arrays of Structures We can declare an array of structures. struct student class[50]; The individual members can be accessed as: class[i].name class[5].roll_number
struct Arrays typedef struct { double x; double y; } point; point pentagon[5]; struct Arrays pentagon : an array of points x y pentagon[1] : a point structure x y x y pentagon[4].x : a double x y x y
Using Arrays of structs StudentRecord class[MAXS]; … for (i=0; i<nstudents; i++) { scanf (“%d%d”, &class[i].midterm, &class[i].final); class[i].grade = (double)(class[i].midterm + class[i].final)/50.0; }
Passing Arrays of structs An array of structs is an array. When any array is an argument (actual parameter), its address is passed, not copied [as for any array] int avg (StudentRec class[MAX]) { ... … } int main ( ) { StudentRec bt01[MAX]; int average; ... average = avg_midpt(bt01) ;
A function using struct array int fail (StudentRecord slist [ ]) { int i, cnt=0; for (i=0; i<CLASS_SIZE; i++) cnt += slist[i].grade == ‘F’; return cnt; }
Arrays within Structures A structure member can be an array: The array element within the structure can be accessed as: a1.marks[2] struct student { char name[30]; int roll_number; int marks[5]; char dob[10]; } a1, a2, a3;
Structure within Structures A structure member can be another structure: struct college_info { int college_id; char college_name[50]; }; struct stud_detail { int class; char name[20]; float percentage; struct college_info college; } student_data;
typedef : An example typedef struct{ float real; float imag; } COMPLEX; COMPLEX a,b,c;
Structure Initialization Structure variables may be initialized following similar rules of an array. The values are provided within the second braces separated by commas. An example: COMPLEX a={1.0,2.0}, b={-3.0,4.0}; a.real=1.0; a.imag=2.0; b.real=-3.0; b.imag=4.0;
Parameter Passing in a Function Structure variables could be passed as parameters like any other variable. Only the values will be copied during function invocation. void swap(COMPLEX a, COMPLEX b) { COMPLEX tmp; tmp=a; a=b; b=tmp; }
An example program #include <stdio.h> typedef struct{ float real; float imag; } COMPLEX; void swap(COMPLEX a, COMPLEX b) { COMPLEX tmp; tmp=a; a=b; b=tmp; }
Example program: contd. void print(_COMPLEX a) { printf("(%f , %f) \n",a.real,a.imag); } main() COMPLEX x={4.0,5.0},y={10.0,15.0}; print(x); print(y); swap(x,y);
Returning structures It is also possible to return structure values from a function. The return data type of the function should be as same as the data type of the structure itself. COMPLEX add (COMPLEX a, COMPLEX b) { COMPLEX tmp; tmp.real = a.real+b.real; tmp.imag = a.imag+b.imag; return(tmp); } Direct arithmetic operations are not possible with Structure variables.
Example-1 Define a structure type student to store the name, roll, and total-marks of any student. Write a program to read this information (from keyboard) for one student and print the same on the screen.
Example-1 CODE:
Example-2 Use the same student structure as described in the Example-1. Define a function to check whether two students are same or not. It returns 1, if the student1 and student2 are same It returns 0, if the student1 and student2 are NOT same
Example-3 Write a C program to perform addition and multiplication of any two complex numbers, taken as input from the terminal.
Exercise Problems Define a structure for representing a point in two-dimensional Cartesian co-ordinate system. Write a function to compute the distance between two given points. Write a function to compute the middle point of the line segment joining two given points. Write a function to compute the area of a triangle, given the co-ordinates of its three vertices.
Problem Statement: Example 4 Write a program which reads two timestamps (hour, minute, second separately in 23:59:59 format) and prints the time difference between them.
Exercise 3 Define a structure data type named date containing three integer members: day, month, and year. Write a program to perform the following tasks: To read data into structure members by a function To print the date in the format: July 11, 2013 To validate the date by another function Example Output: Enter the day, month, and year: 10 9 2016 The date is: September 10, 2016 It is a VALID date Enter the day, month, and year: 31 4 2015 The date is: April 31, 2015 It is an INVALID date
Exercise 4 Use the same date structure as defined in Exercise 1 to store date of birth and current date. Calculate the age of the person.