C structures and unions

Starting to think about objects...

A Structure is a container, it can hold a bunch of things. things.  These things can be of any type.  Structures are used to organize related data (variables) in to a nice neat package.  In general, we can call a structure is a collection of different types of data.  A Structure contains number of data types grouped together.  These data types may be or may not be of same data type.


Structure Members 
Each thing in a structure is called

Each member has a name, a type and a

Names follow the rules for variable

Example Structure Definition
struct StudentRecord { char *name; // student name double hw[3]; // homework grades double test[2]; // test grades double ave; // final average };

Structure declarations
struct S {int a, b; char *p;}; */ /* omit variables 

No variables are declared, but there is now a type struct S that can be referred to later
struct S z; /* omit members */  Given an earlier declaration of struct S, this declares

a variable of that type

typedef struct {int a, b; char *p;} S; /* omit both tag and variables */  This creates a simple type name S (more convenient than struct S)

The struct statement 
Here is an example struct statement.
#include <stdio.h> struct line { int x1, y1; /* co-ords of 1 end of line*/ int x2, y2; /* co-ords of other end */ }; main() { struct line line1; . This defines the variable line1 to be . a variable of type line }

Structure Declaration.
struct tag { type variable-name; type variable-name; type variable-name; }structure variables; struct date { int day; int month int year; };

/* Example program for using a structure*/ #include< stdio.h > void main() { int id_no; char name[20]; char address[20]; char combination[3]; int age; }newstudent; printf(³Enter the student information´); printf(³Now Enter the student id_no´); scanf(³%d´,&newstudent.id_no); printf(³Enter the name of the student´); scanf(³%s´,&new student.name); printf(³Enter the address of the student´); scanf(³%s´,&new student.address); printf(³Enter the cmbination of the student´); scanf(³%d´,&new student.combination); printf(³Enter the age of the student´); scanf(³%d´,&new student.age); printf(³Student information\n´); printf(³student id_number=%d\n´,newstudent.id_no ); printf(³student name=%s\n´,newstudent.name); printf(³student Address=%s\n´,newstudent.address) ; printf(³students combination=%s\n´,newstudent.com bination); printf(³Age of student=%d\n´,newstudent.age); }

The ¶typedef ¶ Keyword.
as in
Without typdef With typedef

struct date { int day ; int month; };

typedef struct date { int day ; int month; };

struct date D1;

date D1;

Accessing Members 
You can treat the members of a struct just like variables.  You need to use the member access operator '.' (pronounced "dot"):
Printf(³%s´,stu.name); stu.hw[2] = 82.3; stu.ave = total/100;

Refrencing Structure elements.
D1.year=1988; D2.day= 2; struct_name element_name




year D1.year


D2 D2.day

Structure Assignments. 

structure variable can be assigned another variable of the same structure type. 
even if the data members are same (in no. and in type ) we cannot assign to different structure type.  Only Assignment (=) is possible for two similar structures.  Other Operations like ( == ) OR ( ! = ) are not possible in most versions of compliers.

Structure Assignment 
You can use structures just like variables:
StudentRecord s1,s2; s1.name = "Joe Student"; « s2 = s1; Copies the entire structure

Structure Assignments.

Eg. typedef struct phoneno { int no; }; phoneno p1,p2; p1.no=6491444; typedef struct pin_no { int no; }; Pin_no n1,n2; n1.no=456010;

Pin no cannot be same as phone no !



//error: type mismatch//

Pointers to Structures 
Pointers to structures are used often.  There is another member access operator used with pointers: ->
StudentRecord *sptr; « sptr->name; cout << "Name is" << sptr->name; cout << "Ave is " << sptr->ave; sptr->ave;

Structures and Arrays 
Array of structures. eg. Struct emp e[10];  Arrays within structure eg. Struct student { char name[20]; int marks[5]; };

#include< stdio.h > { struct info { int id_no; char name[20]; char address[20]; char combination[3]; int age; } struct info std[100];

Void main() { int I,n; printf(³Enter the number of students´); scanf(³%d´,&n); printf(³ Enter Id_no,name address combination age\m´); for(I=0;I < n;I++) scanf(%d%s%s%s%d´,&std[I].id_n o,std[I].name,std[I].address, std[I].combination,&std[I].age); printf(³\n Student information´); for (I=0;I< n;I++) printf(³%d%s%s%s%d\n´, ´,std[I].id_no,std[I].name,std[I].addr ess,std[I].combinatio n,std[I].age); }

E-3 Comparison example 

#include<stdio.h> #include<conio.h> struct student { int age; float avg; }s1,s2,s3;

void main() { clrscr(); s1.age=25; s1.avg=9.5; s2.age=30; s2.avg=8.5; s3=s2; if(s2.age==s3.age && s2.avg==s1.avg) printf("Both S2 and S3 are Same"); else printf("Both are different"); getch(); }

Nested Structures 
structure within a structure  inner structure should be defined before outer structure . Elements are refrenced outermost to innermost.  here Struct addr { int houseno; char locality[20]; char city[20]; }; Struct employee {int name; addr address; }; Struct employee shrey;


Structures and functions. 
Passing structure elements to Functions eg. int s = print (bday.day,bday.month);

/* if one of the elements is an array , it will automatically passed as by refrence as arrays cant be passed by value! */

Member access 
Direct access operator s.m  subscript and dot operators have same precedence and associate left-to-right, so we don¶t need left-toparentheses for sam.pets[0].species  Indirect access s->m: equivalent to (*s).m s Dereference a pointer to a structure, then return a member of that structure  Dot operator has higher precedence than indirection operator , so parentheses are needed in (*s).m (*fido.owner).name or fido.owner->name fido.owner. evaluated first: access owner member * evaluated next: dereference pointer to HUMAN . and -> have equal precedence
and associate left-to-right

This Question was asked at technical exam

for IBM

Give the output of the following program .
Struct point {int x,y;}; Void show(point p) { Printf(³%d \n´,p.x); Printf(³%d \n´, p.y; } Void main() { point U={20,10},V,W; V=U; V.X+=20; W=V; U.Y+=10; U.X+=5; W.X-=5; show(U);show(V);show (W); }

a) 25:20 40:10 35:10

b) 25:20 40:20 35:10

c) 25:10 40:10 35:10

Struct point {int x,y;}; Void show(point p) { Printf(³%d \n´,p.x); Printf(³%d \n´, p.y; }

25:20 40:10 35:10 Y


Void main() { point U={20,10},V,W; V=U; V.X+=20; W=V; U.Y+=10; U.X+=5; W.X-=5; show(U);show(V);show (W); };



Aptitude test Identify error(s) , if any in the following code snippet

struct { short day; short month; short year ; }bdate,joindate;

a) Struct tag missing b) more than 1 variable declared. c) terminated incorrectly

d) NO error !

Correct Ans is

D) NO error !

When Structure tag is missing , it is possible to access the structure tag through the variables created just after !

struct date

{ short day; short month; short year ; }bdate,joindate;

is also correct

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; }; /* either a float xor an int xor a string */

Storage  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

Sign up to vote on this title
UsefulNot useful