CS-250 Data Structures & Algorithms: Mehreen Tahir
CS-250 Data Structures & Algorithms: Mehreen Tahir
LECTURE-3
STRUCTURES
STRUCTURES
– A structure is a group of items in which each item
is identified by its own name
– Each item is called a member (or field) of the
structure
STRUCTURES
struct [structure tag]
{
member definition;
member definition;
...
member definition;
}[one or more structure variables];
Structures
Data type
struct nametype {
char first[10];
char midinit;
char last[20];
};
struct nametype sname, ename;
variables
struct Member Access
• Dot operator (‘.’), e.g.
cout<<sname.first;
ename.midinit=‘m’;
for (i=0;i<20;i++)
sname.last[i]=ename.last[i];
Struct Legal Operations
• Assignment between struct type variables is allowed (ANSI C)
struct nametype {
char first[10];
char mid;
char last[20];
};
struct nametype n1, n2; // you can omit the keyword struct
strcpy (n1.first,"Muhammad");
n1.mid='Y';
strcpy (n1.last,"Javed");
n2=n1; //struct assignment
cout<<n2.first<<" "<<n2.mid<<". "<<n2.last;
Nested Structures
struct addrtype {
char straddr[40];
char city[10];
char state[3];
char zip[6];
};
struct nmadtype {
struct nametype name;
struct addrtype address;
};
struct nmadtype nmad1, nmad2;
Example contd.
• What will the following statements do?
1.nmad1.name.midinit= nmad2.name.midinit;
2.nmad1.address.city[4]=nmad2.name.first[1];
3.for(i=1;i<10;i++)
nmad1.name.first[i]=nmad2.name.first[i];
Structure Implementation
• The amount of storage set aside for a structure is the sum
of storage specified by each of its member types.
• For instance,
struct structtype {
int field1;
float field2;
char field3[10];
};
struct structtype r;
Suppose size of int is 4 bytes, size of float is 4, and size of char
is 1 byte respectively.
Then amount of memory allocated for variable r is ?
structure Implementation
• Answer: 18 bytes
• Usually consecutive storage locations are
allocated to members of structure
• Associated with each member of struct is an
offset that is added to the base address of the
struct to reach that field.
Example
struct nametype {
char first[10];
char mid;
char last[20];
};
nametype n1;
strcpy (n1.first,"Muhammad");
n1.mid='Y';
strcpy (n1.last,"Javed");
char * cp=&(n1.first[0]);
cp+=10;
cout<<*cp;
• Output: ?
• Y