Вы находитесь на странице: 1из 31

C structures and unions

Starting to think about objects...


Structure

 A Structure is a container, it can hold a bunch of 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-Syntax
Structure Members
 Each thing in a structure is called member.

 Each member has a name, a type and a value.

 Names follow the rules for variable names.

 Types can be any defined type.


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 date
struct tag
{
{
int day;
type variable-name;
int month
type variable-name;
int year;
type variable-name;
};
}structure variables;
E-1
/* Example program for using a structure*/
#include< stdio.h > printf(“Enter the age of the student”);
void main() scanf(“%d”,&new student.age);
{ printf(“Student information\n”);
int id_no; printf(“student id_number=
char name[20]; %d\n”,newstudent.id_no);
char address[20]; printf(“student name=
%s\n”,newstudent.name);
char combination[3];
printf(“student Address=
int age; %s\n”,newstudent.address);
}newstudent;
printf(“students combination=
printf(“Enter the student information”); %s\n”,newstudent.combination);
printf(“Now Enter the student id_no”); printf(“Age of student=
scanf(“%d”,&newstudent.id_no); %d\n”,newstudent.age);
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);
The ‘typedef ‘ Keyword.
as in

Without typdef With typedef

struct date
typedef struct date
{ int day ; { int day ;
int month;
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

da month year
y
D1 D1.year

D2

D2.day
Structure Assignments.
 One 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 typedef struct pin_no


{ int no; { int no;
}; };
phoneno p1,p2; Pin_no n1,n2; Pin no cannot
p1.no=6491444; n1.no=456010; be same as
phone no !

p2=p1; n2=n1;

p2=n2;
//error: type
mismatch//
Pointers to Structures
 Pointers to structures are used often.
 There is another member access t e r"!
po in
operator used with pointers: -> a "
ike s l
loo k
it
StudentRecord *sptr;

cout << "Name is" << sptr->name;
cout << "Ave is " << 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];
};
E-2 Void main()
{
int I,n;
printf(“Enter the number of students”);
scanf(“%d”,&n);
#include< stdio.h > printf(“ Enter Id_no,name address combination
{ age\m”);
struct info for(I=0;I < n;I++)
scanf(%d%s%s%s
{ %d”,&std[I].id_no,std[I].name,std[I].address,
int id_no; char name[20]; std[I].combination,&std[I].age);
printf(“\n Student information”);
char address[20]; for (I=0;I< n;I++)
char combination[3]; printf(“%d%s%s%s%d\n”,
int age; ”,std[I].id_no,std[I].name,std[I].address,std[I].co
mbinatio
} n,std[I].age);
struct info std[100]; }
E-3 Comparison example
 #include<stdio.h> void main()
{
 #include<conio.h> clrscr();
 struct student s1.age=25;
s1.avg=9.5;
 { s2.age=30;
 int age; s2.avg=8.5;
 float avg; s3=s2;
if(s2.age==s3.age && s2.avg==s1.avg)
 }s1,s2,s3; printf("Both S2 and S3 are Same");
else
printf("Both are different");

getch();

}
Nested Structures
Struct addr
 structure within a structure
{ int houseno;
 inner structure should be defined
before outer structure . char locality[20];
Elements are refrenced outermost to char city[20];
innermost.
};
 here shrey.address.houseno=3; 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 parentheses for
sam.pets[0].species
 Indirect access s->m: equivalent to (*s).m
 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
. evaluated first: access owner member . and -> have equal precedence and
* evaluated next: dereference pointer to HUMAN associate left-to-right
This Question was asked at technical exam for IBM
Give the output of the following program .
Struct point a) 25:20
{int x,y;};
40:10
Void show(point p)
{ 35:10
Printf(“%d \n”,p.x);
Printf(“%d \n”, p.y;
b) 25:20
}
40:20
Void main()
{ point U={20,10},V,W; 35:10
V=U;
V.X+=20;
c) 25:10
W=V;
U.Y+=10; 40:10
U.X+=5; 35:10
W.X-=5;
show(U);show(V);show (W);
}
Solution A) 25:20
Struct point 40:10
{int x,y;}; 35:10
Void show(point p) X Y
{
Printf(“%d \n”,p.x);
Printf(“%d \n”, p.y;
}
U
Void main()
{ point U={20,10},V,W;
V=U;
V.X+=20; V
W=V;
U.Y+=10;
U.X+=5;
W.X-=5; W
show(U);show(V);show (W);
};
Aptitude test

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

struct { a) Struct tag missing

short day; b) more than 1 variable


declared.
short month;
c) terminated incorrectly
short year ;
d) NO error !
}
bdate,joindate;
Solution

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
Unions
 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 */
Unions
 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

Вам также может понравиться