Professional Documents
Culture Documents
Structures and Unions in 'C'
Structures and Unions in 'C'
STRUCTURES
Structure is a type of data structure in which each individual element differs in type. The
elements of a structure are called members. The structure elements contain integer,
floating point numbers, character arrays, and pointers as their members. Structure act as a
tool for handling logically related data items.
Fields of structure are called structure elements or members. Each member may be of
different type.
Structure is a derived type usually representing a collection of variables of same or
different data type grouped together under a single name.
Use of Structures:
Help to organize Complex data in a meaningful way.
Declaring a Structure:-
Structure is declared using the keyword struct followed by a tag and is enclosed by
curly open { and close } braces. All members of a structure are specified within curly
braces { }.
The general form for defining a structure is:
Here tag refers to the name of the structure. Member1, member2, ---- Member N are
elements of a structure. Structure is terminated with semicolon (;). Initialization is not
allowed within a structure.
1 SMVEC
Computer Programming Unit IV
int pages;
float price;
};
The syntax is
struct tag variable1, variable2, ... ... variable m;
Struct lib_books, book1, book2, book3; declares book1, book2, book3 as variables of type
struct lib_books.
struct lib_books
{
char title [20];
char author [15];
int pages;
float price;
};
struct lib_books, book1, book2, book3;
2 SMVEC
Computer Programming Unit IV
Defining a structure
Syntax:
struct tag
{
data-type member1;
data-type member2;
data-type member-n;
}structure variable(s);
STRUCTURE INITIALIZATION
Structure variable can be initialized at compile time. The storage class must be static.
Structure initializer must be enclosed within curly braces. The order of structure and
structure member must be the same.
For example
main ()
3 SMVEC
Computer Programming Unit IV
{ struct
{
int weight;
float height;
}
student = {70, 170.82};
--------------
--------------
}
This assigns the value 70 to student.weight and 170.82 to student.height. There is one-to-one
correspondence between the members and their initializing values.
The following statements initialize two structure variables. Here it is essential to use tag
name.
main ()
{
struct stud_record
{
int weight;
float height;
}
struct stud_record student1 = {70, 170.82};
struct stud_record student2 = {60, 155.62};
--------------
--------------
}
Example Program:
#include<stdio.h>
#include<conio.h>
struct stud
{
char name [20];
long int regno;
} s3;
4 SMVEC
Computer Programming Unit IV
void main()
{
struct student s1= {Ajay, 100};
struct student s2= {Arun, 101};
printf(\n Name is %s, s1.name);
printf(\n Register Number is %d, s1.regno);
printf(\n Name is %s, s2.name);
printf(\n Register Number is %d, s2.regno);
s3=s1;
printf(\n Name is %s,s3.name);
printf(\n Register Number is %d, s3.regno);
getch();
}
Arrays of Structure
We use structure to describe the format of a number of related variables. For example in
analyzing the marks obtained by a class of students we use template to describe student
name and marks obtained in various subjects and then declare all the students as structure
variables.
In such cases we may declare an array of structures, each element of the array
representing a structure variable. Group of structure variable assigned with same type
stored in an array. Arrays within structures used to store array of values within a
structure.
Example 1:
struct class student [100];
defines an array called student that consists of 100 elements. Each element is defined to be
of the type struct class.
struct marks
{
int subject1;
5 SMVEC
Computer Programming Unit IV
int subject2;
int subject3;
};
main()
{
Struct marks student[30={ {34,45,67},{67,78,89},{57,89,95} };
Example 2:
structure information
{
int id_no;
char name [20];
char address[20];
int age;
}
student[100];
6 SMVEC
Computer Programming Unit IV
scanf(%d,&n);
printf( Enter id_no, name, address, age\n);
for(i=0;i<n;i++)
scanf(%d%s%s%d, &std[i].id_no, std[i].name, std[i].address, &std[i].age);
printf(\n Student information);
for(i=0;i<n;i++)
printf(%d%s%s%d \n, std[i].id_no, std[i].name, std[i].address, std[i].age);
getch();
}
Structure within structure is used to access the structure member placed within another
structure.
Let us consider the following structure defined to store information about the salary of
employees.
this structure defines name, department, basicpay and some allowances. We can
group all the items related to allowance together and declare them under a
substructure as shown below.
7 SMVEC
Computer Programming Unit IV
struct salary
{
char name;
char department;
struct
{
int dearness_allowance;
int house_rent_allownace;
int city_allownace;
}
allowance;
}
employee;
This salary structure contains a member named allowance, which itself is structure with three
members. The members contained in the inner structure namely dearness,
house_rent ant city can be referred as
employee.allowance.dearness
employee.allowance.house_rent
employee.allowance.city
Example Program: Employee details using nested structures
#include<stdio.h>
#include<conio.h>
void main()
{
struct employee
{
int empno;
char empname [20];
struct employ_add
{
int no;
char street;
char area;
8 SMVEC
Computer Programming Unit IV
char city;
} address;
char deptname;
float salary;
} emp1;
printf(Enter empno,empname,deptname,salary of the employee\n);
scanf(%d%s%s%f,&emp1.empno,emp1.empname,emp1.deptname,&emp1.salary);
printf (Enter the address of the employee : ( no,street name, area name, city) \n);
scanf(%d%s%s%s,&emp1.address.no, emp1.address.street, emp1.address.area,
emp1.address.city);
printf\n Employee Details);
printf(\n Employee No = %d,emp1.empno);
printf(\n Employee Name = %s,emp1.empname);
printf(\n Department Name = %s,emp1.deptname);
printf(\n Employee Salary = %0.2f,emp1.salary);
printf(\n Employee Address);
printf(\n House number: %d, emp1.address.no);
printf(\n Street name:%s, emp1.address.street);
printf(\n Area name:%s, emp1.address.area);
printf(\n City name:%s, emp1.address.city);
getch();
}
C supports the passing of structure values as arguments to functions. There are three
methods by which the values of structure can be transferred from one function to another.
1. Pass each member of the structure as an actual argument of the function call. The
actual argument are then treated independently like ordinary variables. This is
most simple method and becomes unmanageable and inefficient when the
structure size is large.
9 SMVEC
Computer Programming Unit IV
2. Passing a copy of the entire structure to the called function. Since the function is
working on the copy of the structure any changes to structure members within the
function are not reflected in the original structure (ie in the calling function). It is
therefore necessary for the function to return the entire structure back to the
calling function.
3. Third approach employs a concept called pointers to pass the structure as an
argument. In this case the address location of the structure is passed to the called
function. The function can access indirectly the entire structure and work on it.
In this we will discuss about the second method, while the third approach using pointers is
discussed in pointers concept.
function_name(structure_variable_name);
10 SMVEC
Computer Programming Unit IV
};
struct stores update(struct stores product, float p, int q);
float mul (struct stores stock);
main()
{
float p_increment, value;
int q_increment;
struct stores item=(XYZ, 26.54.17);
printf(\n Input increment values :);
printf(Price increment and quantity increment\n);
scanf(%f %d, &p_increment, &q_increment);
printf(updated values of item\n\n ) ;
printf(name : %s \n, item.name);
printf(price :%f \n, item.price);
printf(quantity: %d \n,item.quantity);
value=mul(item) ;
printf( \n Value of the item = %f \n, Value);
}
struct stores update(struct stores product, float p, int q)
{
product.price += p;
product.quantity += q;
return(product);
}
float mul(struct stores stock)
{
return(stock.price*stock.quantity);
}
UNIONS
11 SMVEC
Computer Programming Unit IV
own memory location, whereas members of unions have same memory locations. It can
accommodate one member at a time in a single area of storage.
Unions also contains members of types int, float, long, arrays, pointers and so on. It
allocates fixed specific bytes of memory for access of data types irrespective of any data
type.
Like structures, a union can be declared using the keyword union as follows
union item
{
int m;
float x;
char c;
}code;
This declares a variable code of type union item. The union contains three members, each
with a different data type. However, we can use only one of them at a time. This is due to
the fact that only one location is allocated for a union variable, irrespective of its size.
The compiler allocates a piece of storage that is large enough to hold the largest variable
type in the union. In the declaration above, the member x requires 4 bytes which is the
largest among the members. The below diagram shows how all the three variables share
the same address.
To access a union member, we can use the same syntax that we use for structure
members.
code.m
code.x
code.c
12 SMVEC
Computer Programming Unit IV
SIZE OF STRUCTURES
We normally use structures, unions and arrays to create variables of large sizes. The
actual size of these variables in terms of bytes may change from machine to machine. we
may use the unary operator sizeof to tell us the size of the structure or any other
variable.
sizeof(struct x)
will evaluate the number of bytes required to hold all the members of the structure x.
POINTERS
A Pointer is a derived data type in C. It is built from one of the fundamental data types
available in C. Pointers contain memory addresses as their values. Pointer is a variable
that holds the address of another data item or variable.
13 SMVEC
Computer Programming Unit IV
Pointer is also a variable that represents the location (not the value) of data item such as a
variable or an array element.
Since these memory addresses are the locations in the computer memory where program
instructions and data are stored, pointers can be used to access and manipulate data stored
in the memory.
Advantages of using pointer:
It increases the execution speed and save data storage space.
It is used to access and manipulate data stored in the Memory.
It is used to return multiple values from a function.
It supports Dynamic Memory Management.
It is used to handle data structures like structure, linked lists, queues, stacks and trees.
It reduces the length and complexity of programs.
It improves the efficiency of program.
Used to pass information back and forth between function and reference point.
Provide ways to represent Multi Dimensional arrays.
Data-type *pt-name;
Here pt-name refers to valid pointer variable name. * is called as indirection operator
also known as dereferencing operator.
Data-type refers to a valid C data type. Pointer variable must be followed by * sign.
Example: int *x;
float *f;
char *y;
In the first statement x is an integer variable and it tells the compiler that it holds the
address of any integer variable. In the same way f is a float pointer, which stores the
address of any float variable and y is a character pointer that stores the address of any
character variable.
14 SMVEC
Computer Programming Unit IV
When a pointer is dereferenced, the value stored at that address by the pointer is
retrieved.
Normal variable provides direct access to its own values, whereas a pointer provides
indirect access to the values of the variable whose address it stores.
When a pointer is declared, the star indicates that it is a pointer, not a normal variable.
The & is the address operator and it represents the address of the variable. The %u is
used with printf () function for printing the address of a variable. The address of any
variable is a whole number. The operator & immediately preceding the variable returns
the address of the variable.
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf(enter the number:);
scanf(%d, &n);
printf(Value of N: %d\n,n);
printf(Address of N:%u\n, &n);
getch();
}
OUTPUT:
Enter a number: 20
Value of N : 20
Address of N : 4066
15 SMVEC
Computer Programming Unit IV
General form:
datatype *pt_name=value;
16 SMVEC
Computer Programming Unit IV
p=&value;
n=*p;
In first line value and n are declared as integer variables and p as a pointer variable
pointing to integer. The second line assigns the value 560 to value and the third line
assigns the address of value to the pointer variable p. The fourth line contains the
indirection operator *.
When the operator * is placed before a pointer variable in an expression, the pointer
returns the value of the variable of which the pointer value is the address. In this case *p
returns the value of the variable value, because p is the address of value.
Example Program: Display the contents of the variable their address using pointer
variable
#include< stdio.h >
#include<conio.h>
void main()
{
int num, *intptr;
float x, *floptr;
char ch, *cptr;
num=123;
x=12.34;
ch=a;
intptr=&x;
cptr=&ch;
floptr=&x;
printf(Num %d stored at address %u\n,*intptr,intptr);
printf(Value %f stored at address %u\n,*floptr,floptr);
printf(Character %c stored at address %u\n,*cptr,cptr);
getch();
}
In this chapter Pointers can be applied to four different categories. They are
1. Pointers and arrays
2. Pointers and strings
3. Pointers and functions
17 SMVEC
Computer Programming Unit IV
1 2 3 4 5
1000 1002 1004 1006 1008
The name x is defined as a constant pointer pointing to the first element, x[0] and
therefore the value of x is 1000, the location where x[0] is stored.
For example
x=&x[0]=1000
If we declare p as an integer pointer, then we can make the pointer p to point to the array
x by the following assignment
p=x;
This is equivalent to p= &x[0];
Now we can access every value of x using p++ to move from one element to another.
The relationship between p and x is shown as
p=&x[0]=1000;
p+1=&x[1]=1002;
p+2=&x[2]=1004;
p+3=&x[3]=1006;
p+4=&x[4]=1008;
18 SMVEC
Computer Programming Unit IV
OUTPUT
ELEMENT VALUE ADDRESS
x[0] 1 200
x[1] 2 202
x[2] 3 204
x[3] 4 206
x[4] 5 208
sum = 15
&x[0] = 200
p = 210
19 SMVEC
Computer Programming Unit IV
ARRAY OF POINTERS
Array of pointers contains collection of address. The address may be the address of
variable or array elements. So far we have studied array of different standard data types
such as array of int, float, character and so on.
In the same way the C language also supports array of pointers. It is nothing but a
collection of addresses. Here we store addresses of variables for which we have to
declare an array as a pointer.
Example Program: Biggest of N numbers in array using pointers
#include<stdio.h>
#include<conio.h>
void main()
{
int i, n,a[25],*ptr;
printf(\ Enter the number of elements : );
scanf(%d,&n);
printf(\n Enter the array elements : );
ptr=a;
for(i=0;i<n;i++)
scanf(%d, (ptr+i));
big=*(ptr+0);
for(i=1;i<n;i++)
{
if(big<*(ptr+i))
big=*(ptr+i);
}
printf(\n The biggest element in the array is %d, big);
getch();
}
20 SMVEC
Computer Programming Unit IV
Strings are treated like character arrays and therefore, they are declared and initialized as
follows.
char str[5]=good;
The compiler automatically inserts the null character\0 at the end of the string. C
supports an alternative method to create strings using pointer variables of type char. For
example
char *str=good;
This creates a string for the literal and then stores its address in the pointer variable
str. The pointer str now points to the first character of the string good as:
g o o d \0
str
We can also us the run-time assignment for giving values to a string pointer. For example
char * string1;
string1=good;
Note that the assignment
string1=good; is not a string copy, because the variable string1 is a
pointer, not a string.
C does not support copying one string to another through assignment operation.
We can print the content of the string string1 using either printf or puts function as
follows
printf(%s, string1);
puts(string1);
Example Program: Program to determine the length of a character string using
pointers
#include<stdio.h>
#include<conio.h>
void main()
{
char *name;
int length;
21 SMVEC
Computer Programming Unit IV
char *cptr=name;
name=India;
printf(%s\n,name);
while(*cptr !=\0)
{
printf(%c is stored at address %u\n, *cptr, cptr);
cptr++;
}
length =cptr-name;
printf(\n Length of the string=%d\n, length);
}
OUTPUT
INDIA
I is stored at address : 24
N is stored at address : 25
D is stored at address : 26
I is stored at address : 27
A is stored at address : 28
POINTERS & FUNCTIONS
Pointers are passed to a function as Arguments. When it is passed, the data item within a
pointer variable gets changed within the function and then the values are returned to the
Calling program. Pointers are passed to a function in two main ways. They are
(i) Call by value
(ii) Call by reference
Call by value :
The process of passing the actual value of variables to a function is called call by
value. In call by value, a copy of the variable is made and passed to the function as
argument. Changes made to parameters of function have no effect on variable which call
the function. (Because changes are made only inside the function).
22 SMVEC
Computer Programming Unit IV
The values from calling function are passed as arguments to the called function. When a
value is passed to a function actual argument value is copied to the called function
variable. The value of actual argument within the calling function will not be altered.
Example Program 1:
#include<stdio.h>
#include<conio.h>
void add(int);
void main()
{
int x=5;
clrscr();
printf(\n Value of x before function call is %d,x); // 5
add(x);
printf(\n Value of x after function call is %d,x); // 5
getch();
}
void add(int y)
{
y=y+5;
printf(\n Value of x in called fuinction is %d,y); // 10
}
OUTPUT
Value of x before function call is 5
Value of x in called function is 10
Value of x after function call is 5
Example Program 2:
#include<stdio.h>
#include<conio.h>
23 SMVEC
Computer Programming Unit IV
void main()
{
int x=50, y=70;
interchange(x,y);
printf(x=%d y=%d,x,y);
}
interchange(x1,y1)
int x1,y1;
{
int z1;
z1=x1;
x1=y1;
y1=z1;
printf(x1=%d y1=%d,x1,y1);
}
OUTPUT
X=70 Y=50
X=50 Y=70
Example Program 3:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
void swap(int,int);
printf("Enter 2 numbers:");
scanf("%d%d",&a,&b);
printf("\n The values before swap a=%d b=%d",a,b);
swap(a,b);
printf("\n The values after swap a=%d b=%d",a,b); getch();
}
void swap(int x,int y)
{
24 SMVEC
Computer Programming Unit IV
int temp;
temp=x;
x=y;
y=temp;
printf("\n Values inside the function a=%d b=%d",x,y);
}
OUTPUT
The values before swap a=20 b=30
Values inside the function a=30 b=20
The values after swap a=20 b=30
Advantages:
Expressions can be passed as arguments.
Unwanted changes to the variables in the calling function are avoided.
Disadvantages:
Information cannot be passed back from the calling function to the called function
through arguments.
Call by reference:
The process of calling a function using pointers to pass the address of variable is called as
call by reference or call by address or call by location.
The addresses of actual arguments in calling function are copied into formal arguments of
called function.
Any change made to parameters of function will affect the variables, which call the
function. When address is passed to a function the parameters receiving the address
should be pointers. The function that is called by reference can change the values of the
variable used in the call.
25 SMVEC
Computer Programming Unit IV
void main()
{
int b=5;
printf(\n The value of b before function call is %d,b); // 5
add(&b);
printf(\n The value of b after function call is %d,b); // 7
getch();
}
void add(int *a)
{
a=a+2;
printf(\n The value of b in called function is %d,b); // 5
}
Example Program 2: Call by reference
#include<stdio.h>
#include<conio.h>
void main()
{
int x=50, y=70;
interchange(&x,&y);
printf(x=%d y=%d,x,y);
getch();
}
interchange(x1,y1)
int *x1,*y1;
{
int z1;
z1=*x1;
*x1=*y1;
*y1=z1;
printf(*x=%d *y=%d,x1,y1);
}
26 SMVEC
Computer Programming Unit IV
To pass entire array to a function pass the address of the first array element with the size
of array to the called function.
#include<stdio.h>
#include<conio.h>
void display(int *x);
void main(}
{
int a[]={1,2,3,4,5};
27 SMVEC
Computer Programming Unit IV
int i;
display(a);
getch();
}
void display(int *x)
{
int i;
for(i=0;i<5;i++)
printf(%d\t,x[i]);
}
OUTPUT:
12 345
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5],i;
void multiply(int *);
printf("Enter 5 numbers \n");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
multiply(a);
printf("The values in array a after executing function is \n");
for(i=0;i<5;i++)
printf("%d\n",a[i]);
getch();
}
void multiply(int *p)
{
int i;
28 SMVEC
Computer Programming Unit IV
for(i=0;i<5;i++)
{
*p=*p*2;
*p++; } }
POINTERS TO FUNCTION
A function like a variable has a type and an address location in the memory. It is
therefore possible to declare a pointer to a function, which can be used as an argument in
another function.
Pointer to a function contains the address of function in memory. Pointers are passed to a
function as arguments.
It helps to use it as argument in another function. The general form for declaring pointer
to a function is
returntype (*fptr)();
Syntax :
where fptr is a pointer to a function. fptr returns the value of type return type.
Example Program: Pointer to Function
int (*ptr)(int);
#include<stdio.h>
void main()
{
int num;
clrscr();
printf(\n Enter a number :);
scanf(%d,&num);
printf(\n The sum of squares of first %d numbers is %d,num,sum(square,num));
getch();
}
int sum(int (*fptr)( ),int n)
{
int add,i;
for(i=;i<=n;i++)
Output:-
add +=(*fptr)(i);
return 0;
}
int square( int i)
{ return(i*i); }
POINTERS AND STRUCTURES
Pointer and structure can be used together in a program. Here arrow operator (->) is used.
Arrow operator is also called member selection operator.
Consider the following declaration
struct shop
{
char name[30];
int number;
float price;
} product[2], *ptr;
This statement declares product as an array of two elements, each of type stuct shop and ptr
as a pointer to data objects of the type struct shop. The assignment
ptr-product;
would assign the address of the 0th element of product to ptr. That is the pointer ptr will
now point to product[0]. Its members can be accessed using the following notation.
ptr name
ptr number
ptr price
30 SMVEC
Computer Programming Unit IV
OUTPUT
Input
Fan 5 2000
Light 10 200
Tv 22 10000
Output
31 SMVEC
Computer Programming Unit IV
Fan 5 2000.00
Light 10 200.00
Tv 22 10000.00
32 SMVEC