Structures & Unions
Structures
• A Structure is a collection of related data items, possibly of different
types.
• A structure type in C is called struct.
• A struct is heterogeneous in that it can be composed of data of
different types.
• In contrast, array is homogeneous since it can contain only data of
the same type.
Structures
• Structures hold data that belong together.
• Examples:
• Student record: student id, name, major, gender, start year, …
• Bank account: account number, name, currency, balance, …
• Address book: name, address, telephone number, …
• In database applications, structures are called records.
3
Structures
• Individual components of a struct type are called members (or
fields).
• Members can be of different types (simple, array or struct).
• A struct is named as a whole while individual members are named
using field identifiers.
• Complex data structures can be formed by defining arrays of
structs.
struct basics
• Definition of a structure:
struct <struct-type>{
<type> <identifier_list>; Each identifier
<type> <identifier_list>; defines a member
... of the structure.
} ;
• Example:
struct Date {
int day; The “Date” structure
int month; has 3 members,
int year;
day, month & year.
} ;
struct examples
• Example:
struct StudentInfo{
int Id;
int age; The “StudentInfo”
char Gender; structure has 4 members
double CGA;
}; of different types.
• Example:
struct StudentGrade{
char Name[15];
char Course[9];
int Lab[5];
The “StudentGrade”
int Homework[3]; structure has 5
int Exam[2];
members of
};
different array types.
struct examples
• Example:
struct BankAccount{
char Name[15]; The “BankAcount”
int AcountNo[10]; structure has simple,
double balance; array and structure
};
types as members.
• Example:
struct StudentRecord{
char Name[15];
The “StudentRecord”
int Id;
char Dept[5]; structure has 4
char Gender; members.
};
struct basics
Declaration of a variable of struct type:
<struct-type> <identifier_list>;
Example:
StudentRecord Student1, Student2;
Name Name
Student1 Student2
Id Gender Id Gender
Dept Dept
Student1 and Student2 are variables of
StudentRecord type.
Accessing structure members
• The members of a struct type variable are
accessed with the dot (.) operator:
Student1
<struct-variable>.<member_name>;
Name
• Example:
Id Gender
strcpy(Student1.Name, “Amit");
Student1.Id = 12345; Dept
strcpy(Student1.Dept, "COMPUTER");
Student1.gender = 'M’;
Amit
printf(“%d”, student1.Id); 12345 M
COMPUTER
Declaring Structures (struct)
Does Not Reserve Space Reserves Space
struct my_example struct my_example
{ {
int label; int label;
char letter; char letter;
char name[20]; char name[20];
}; } mystruct ;
Example #include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
int book_id;
};
void main( )
{
struct Books Book1;
strcpy( Book1.title, "Programming");
strcpy( Book1.author, "ABC");
Book1.book_id = 123456;
printf( "title : %s\n", Book1.title);
printf( "author : %s\n", Book1.author);
printf( "id : %d\n", Book1.book_id);
}
Structure initialization
#include <stdio.h>
struct record {
int weight;
float height;
}s1={60,180.65};
void main( )
{
struct record s2={54,200.50};
printf("%d \t %f \n",s1.weight,s1.height);
printf("%d \t %f",s2.weight,s2.height);
}
Array of structure
#include <stdio.h>
struct marks {
int sub1;
int sub2;
int sub3;
};
struct marks m[3];
m[0].sub1=45;
void main( ) m[0].sub2=55;
m[0].sub3=65;
{
struct marks m[3]={
{45,55,65},{85,59,62},{59,57,63},
};
int i;
for(i=0;i<=2;i++)
printf("%d %d %d \n",m[i].sub1,m[i].sub2,m[i].sub3);
Structure and function
#include <stdio.h>
struct student { void show(struct student s)
{
char name[20];
printf("Your Name: %s \t", s.name);
int age; printf("Your Age: %d", s.age);
}; }
void show(struct student);
void main()
{
struct student s1;
printf("Enter your name: ");
scanf("%s", s1.name);
printf("Enter your age: ");
scanf("%d", &s1.age);
show(s1); /* passing struct to function */
}
• A union is a user defined type similar to
structs in C except for one key difference.
Unions • Structs allocate enough space to store all its
members wheres unions allocate the space
to store only the largest member.
union items
{
int m;
Unions float x;
char c
}code;
Example
#include <stdio.h>
union Data
{
int i;
float f;
char name[20];
};
void main( )
{
union Data d;
d.i = 100;
d.f = 20.5;
strcpy( d.name, "Krishna");
printf( "%d \n %f \n%s", d.i, d.f, d.name);
1936290379
}
8495533826379695000000000000000.000000
Krishna
Example #include <stdio.h>
union Data
{
int i;
float f;
char name[20];
};
void main( )
{
union Data d;
d.i = 100;
printf( "i : %d\n", d.i);
d.f = 20.5;
printf( "f : %f\n", d.f);
strcpy( d.name, "My name is amit");
printf( "name : %s\n", d.name);
i : 100
} f : 20.500000
name : My name is amit
Pointers
Pointers
• A pointer is a variable that represents the location (rather than the
value) of a data item.
• They have a number of useful applications.
➢ Used to change variables inside a function (reference parameters)
➢ Used to remember a particular member of a group (such as an array)
➢ Used in dynamic memory allocation (especially of arrays)
➢ Used in building complex data structures (linked lists, stacks, queues, trees,
etc.)
Basic Concept
• Within the computer memory, every stored data item occupies one
or more contiguous memory cells.
• The number of memory cells required to store a data item depends on its type
(char, int, double, etc.).
• Whenever we declare a variable, the system allocates memory
location(s) to hold the value of the variable.
• Since every byte in memory has a unique address, this location will also have
its own (unique) address.
• Consider the statement
int x = 50;
• This statement instructs the compiler to allocate a location for the integer
variable x, and put the value 50 in that location.
• Suppose that the address location chosen is 1300.
X ➔ variable
50 ➔ value
1380 ➔ address
• During execution of the program, the system always associates the
name x with the address 1300.
• The value 50 can be accessed by using either the name x or the address
1300.
• Since memory addresses are simply numbers, they can be assigned
to some variables which can be stored in memory.
• Such variables that hold memory addresses are called pointers.
• Since a pointer is a variable, its value is also stored in some memory location.
• Suppose we assign the address of x to a variable p.
• p is said to point to the variable x.
Variable Value
Address p = &x;
x 50
1300
p 1300 1 1300 50
2505
p x
Accessing the Address of a Variable
• The address of a variable can be determined using the ‘&’
operator.
• The operator ‘&’ immediately preceding a variable returns the address of
the variable.
• Example:
p = &x;
• The address of x (1300) is assigned to p.
• The ‘&’ operator can be used only with a simple variable or an
array element.
&distance
&x[0]
&x[i-2]
Following usages are illegal:
&235
• Pointing at constant.
int arr[20];
:
&arr;
• Pointing at array name.
&(a+b)
• Pointing at expression.
Example
#include <stdio.h>
main()
{
int a;
float b;
double d;
char c;
a = 100; b = 12.5; c = 1.36; d = 12345.55; c = 'P';
printf (" a is stored in location %d \n", &a) ;
printf (" b is stored in location %d \n", &b) ;
printf (" d is stored in location %d \n", &d) ;
printf (" c is stored in location %d \n", &c) ;
}
a is stored in location 6487580
b is stored in location 6487576
d is stored in location 6487568
c is stored in location 6487567
Pointer Declarations
• Pointer variables must be declared before we use them.
• General form:
data_type *pointer_name;
Three things are specified in the above declaration:
1. The asterisk (*) tells that the variable pointer_name
is a pointer variable.
2. pointer_name needs a memory location.
3. pointer_name points to a variable of type
data_type.
Ex.
• Example:
int *ptr;
float *point;
• Once a pointer variable has been declared, it can be made to
point to a variable using an assignment statement like:
int *p, x;
:
p = &x;
• This is called pointer initialization.
Accessing a Variable Through its Pointer
• Once a pointer has been assigned the address of a variable, the
value of the variable can be accessed using the indirection
operator (*).
int a, b;
int *p;
:
p = &a;
Equivalent to b=a
b = *p;
Example 1
#include <stdio.h>
main()
{
int a, b;
int c = 5;
int *p; Equivalent
a = 4 * (c + 5) ;
p = &c;
b = 4 * (*p + 5) ;
printf (“a=%d b=%d \n”, a, b) ;
}
Example 2
#include <stdio.h>
main()
{
int x, y;
int *ptr;
x = 10 ;
ptr = &x ;
y = *ptr ; ptr= 6487568
printf ("ptr= %d\n",ptr ); *ptr= 10
printf ("*ptr= %d\n", *ptr) ; y= 10
printf ("y= %d\n", y) ; Now x = 50
*ptr = 50;
printf ("Now x = %d \n", x);
}
Pointer Expressions
• Like other variables, pointer variables can be used in expressions.
• If p1 and p2 are two pointers, the following statements are valid:
sum = *p1 + *p2 ;
prod = *p1 * *p2 ;
prod = (*p1) * (*p2) ;
*p1 = *p1 + 2;
x = *p1 / *p2 + 5 ;
• What are not allowed?
• Add two pointers.
p1 = p1 + p2 ;
• Multiply / divide a pointer in
an expression.
p1 = p2 / 5 ;
p1 = p1 – p2 * 10 ;
Example: passing arguments by value
#include <stdio.h>
main() a and b
{
int a, b; do not
a = 5 ; b = 20 ; swap
swap (a, b) ;
printf (“\n a = %d, b = %d”, a, b); Output
}
a = 5, b = 20
void swap (int x, int y)
{
int t ;
t=x;
x=y;
y=t; x and y swap
}
Example: passing arguments by reference
#include <stdio.h>
main()
{ *(&a) and *(&b)
int a, b;
a = 5 ; b = 20 ; swap
swap (&a, &b) ;
printf (“\n a = %d, b = %d”, a, b);
}
void swap (int *x, int *y)
{ Output
int t ;
t = *x ; a = 20, b = 5
*x = *y ; *x and *y
*y = t ; swap
}