Unit 4
Unit 4
Unit 4
STRUCTURES
Structure is a user defined data type which allow to combine different datatype.
Advantages
DEFINITION OF STRUCTURES
As variables are defined before they use in the program, structures are also defined and
declared before they are used.
A structure definition forms a template that may be used to create structure objects. The
variables that make up the structure are called members of the structure.
The structure definition associated with the structure name is referred as tagged
structure. It does not create an instance of a structure and does not allocate any
memory.
struct tagname
{
datatype member1;
datatype member2;
…………………………
…………………………
datatype membern;
};
Where,
struct is the keyword which tells the compiler that a structure is being defined.
tagname is the name of the structure.
member1, member2 … are called members of the structure. The members are
declared within curly braces.
The closing brace must end with the semicolon.
Page 2 of 18
struct student
{
int regno;
char name[50];
float avgmarks;
}; // no memory is allocated for the structure
struct is the keyword which tells the compiler structure is being defined.
student is an identifier representing the structure name (tagname).
name, regno and avgmarks are members of a structure and are themselves are
not variables. They do not occupy any memory.
Memory is not reserved for the structure definition since no variables are associated with
the structure definition. The members of the structure do not occupy any memory until
they are associated with the structure variables.
where, struct is the keyword. tagname is the name of the structure. Structure variables
are separated by comma, followed by semicolon.
now a variable of type struct student (derived type) is created, the memory is allocated
for the variable s1.
Page 3 of 18
The following figure shows the memory organization for the above example.
s1
regno name avgmarks ->
< 2 Bytes > < 50 Bytes > < 4 Bytes >
The number of bytes allocated for the structure variable is the sum of sizes of the
individual members. In the above example the size of s1=56 bytes (2+50+4).
Note: Normally, structure definition appears at the beginning of the program file, before
any variables or functions defined.
INITIALIZATION OF STRUCTURES
The rules for structure initialization are similar to the rules for array initialization. The
initializes are enclosed in braces and separate by commas. They must match their
corresponding types in the structure definition.
Consider the structure definition for student with three fields regno, name, and
avgmarks. The initialization of variable can be done as shown below,
struct student
{
int regno;
char name[50];
float avgmarks;
};
ACCESSING STRUCTURES
We know that variables can be accessed and manipulates using expressions and
operators. On the similar lines, the structure members can be accessed and manipulated.
The members of a structure can be accessed by using dot(.) operator.
Structures use a dot (.) operator to refer its elements, also known as period operator.
Before dot, there must always be a structure variable. After the dot, there must always
be a structure element.
structurevariablename . structuremembername
For example, consider the example as shown below,
struct student
{
int regno;
char name[50];
float avgmarks;
};
Array of structures
Array of structures is nothing but collection of structures. This is also called as structure
array in C.
#include <stdio.h>
#include <conio.h>
#include<string.h>
void main()
{
struct student
{
int regno;
char name[50];
float avgmarks;
};
struct student s[2];
int i;
clrscr();
// 1st student's record
s[0].regno=186;
strcpy(s[0].name,"Mohith G Kalyan");
s[0].avgmarks = 78.8;
A structure can be passed to any function from main function or from any sub
function.
Structure definition will be available within the function only.
It won‟t be available to other functions unless it is passed to those functions by
value or by address(reference).
Else, we have to declare structure variable as global variable. That means,
structure variable should be declared outside the main function. So, this structure
will be visible to all the functions in a C program.
Example program – passing structure to function in C by value:
In this program, the whole structure is passed to another function by value. It
means the whole structure is passed to another function with all members and their
values. So, this structure can be accessed from called function. This concept is very
useful while writing very big programs in C.
#include <stdio.h>
#include <conio.h>
#include<string.h>
struct student
{
int regno;
char name[50];
float avgmarks;
};
void main()
{
struct student s;
clrscr();
s.regno=186;
strcpy(s.name,"Mohith G Kalyan");
s.avgmarks = 78.8;
gkstrtfun(s);
getch();
}
Page 7 of 18
NESTED STRUCTURES
A structure which includes another structure is called nested structure i.e a structure can
be used as a member of another structure.
struct tag_name1
{
type1 member1;
…….
…….
};
struct tag_name2
{
type1 member1;
……
……
struct tag_name1 var;
……
};
outer_structure_variable.innerstructurevariable.membername
Example: Consider the student information regno, name, DOB and avgmarks. The DOB
consists of day, month, and year. It can be defined as shown below,
struct data
{
int day;
int month;
int year;
};
Page 8 of 18
struct student
{
int regno;
char name [50];
struct data dob;
float avgmarks;
};
struct student s;
Note that the above structure consists of a member identified by dob whose type is struct
data.
The members contained in the inner structure namely day, month and year can be
referred to as
s.dob.day
s.dob.month
s.dob.year
UNIONS
union tagname
{
datatype1 member1;
datatype2 member2;
…………………………..
.………………………….
};
union is the keyword which tells the compiler that a union is being defined.
member1, member2, … are called members(or fields) of the union.
The members are declared within curly braces.
The compiler allocates a piece of storage that is large enough to hold the largest
variable type in the union.
There should be semicolon at the end of closing braces.
POINTER
A variable which holds address of another variable is called a pointer variable. Example:
If x is a variable and address of x is stored in a variable p (i.e. p=&x), then the variable p
is called a pointer variable.
(Note: A pointer variable should contain only the addresses)
datatype *identifier;
Here datatype indicates any data type like int, char, float etc. It can be derived or user
defined data type also.
Identifier is the name given to the pointer variable. It should be a valid user-defined
variable name. The asterisk(*) in between type and identifier indicates that the identifier
is a pointer variable.
I Location name
5 Value at location
Here the location number 4012 is not a number to be relied upon. The important point is
I‟s address in memory is a number. To print the address is the following program:
Page 12 of 18
We use indirection operator(*) to access the values of the variables through pointers.
Example:
int x=10, *p;
p=&x;
printf(“%d”,*p);
a) Pass by value: Whatever the changes done inside the function is not reflected
outside the function.
If the values of the formal parameters changes in the function, but the
values of the actual parameters are not changed. Then it is called pass by
value or call by value.
Page 13 of 18
After execution of this program, the first printf() function prints the value
x=10,y=20, then it calls the function swap(x,y), In the function swap(x,y), the
values of x and y are interchanged. So in the swap(x,y), the printf() function
prints x=20 and y=10, then the control will transferred to main() function and the
printf function prints the value x=10 and y=20. This indicates that, in call by
value, whatever modifications done to the formal parameters, it will be reflected
in that particular functions, outside the functions the value will be remain same as
actual parameter.
If the values of the formal parameters changes in the function, and the
values of the actual parameters are also changed. Then it is called pass
by reference or call by address.
Page 14 of 18
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[25],str2[50];
int i=0,j=0;
clrscr();
printf("Enter First String: ");
gets(str1);
printf("Enter Second String: ");
gets(str2);
while(str1[i]!='\0')
{
i++;
}
while(str2[j]!='\0')
{
str1[i]=str2[j];
j++;
i++;
}
str1[i]='\0';
printf("\nConcatenated String is %s",str1);
getch();
}
Page 16 of 18
malloc( )
The name malloc stands for "memory allocation". The function malloc() reserves a block
of memory of specified size and return a pointer of type void which can be casted into
pointer of any form.
Syntax of malloc()
ptr=(cast-type*)malloc(byte-size)
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of
memory with size of byte size. If the space is insufficient, allocation fails and returns
NULL pointer.
ptr=(int*)malloc(100*sizeof(int));
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes
respectively and the pointer points to the address of first byte of memory.
calloc( )
The name calloc stands for "contiguous allocation". The only difference between malloc()
and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates
multiple blocks of memory each of same size and sets all bytes to zero.
Syntax of calloc()
ptr=(cast-type*)calloc(n,element-size);
This statement will allocate contiguous space in memory for an array of n elements. For
example:
ptr=(float*)calloc(25,sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements each of
size of float, i.e, 4 bytes.
Page 18 of 18
free( )
Dynamically allocated memory with either calloc() or malloc() does not get return on its
own. The programmer must use free() explicitly to release space.
syntax of free()
free(ptr);
This statement causes the space in memory pointer by ptr to be deallocated.
realloc( )
If the previously allocated memory is insufficient or more than sufficient. Then, you can
change memory size previously allocated using realloc().
Syntax of realloc()
ptr=realloc(ptr,newsize);
Here, ptr is reallocated with size of newsize.