Unit V
Unit V
Unit V
Pointer concepts - Pointers & Arrays, Structure concepts - Defining, Declaring, Accessing Member
Variables, Structure within Structure - Union - File Management in C- Dynamic Memory Allocation.
POINTERS
Definition
A pointer is a variable that stores the address of another variable. A pointer represents the
location of a data item in the memory. It is a derived data type used in C Language.
Syntax
datatype *variable_name;
Example1
int *ptr;
ptr = &a;
Here,
ptr Pointer Variable, it holds the memory address of another variable ‘a’
&a Address of variable ‘a’, it is stores in pointer variable ‘prt’
Example2
a Variable
10 Value
2000 Address
Now,
int *p; //Pointer variable
p = &a; //Address of ‘a’ is assigned to pointer
Hence,
p = 2000
*p = 10
Pointer Operator
In order to create pointer to a variable use “*” operator and to find the address of variable use
“&” operator.
c. Pointer-to-pointer
Usually pointer variable stores the address of another variable. Pointer-to-pointer stores
address of another pointer variable.
Example
**p2 =
*p1 = &a ***p3 = &p2
&p1
Variable a p1 p2 p3
Value 10 1000 2000 3000
Address 1000 2000 3000 4000
Here,
*p1 Pointer
**p2, ***p3 Pointer-to-pointer
p1 = 1000
*p1 = 10
p2 = 2000
*p2 = 1000
**p2 = 10
p3 = 3000
*p3 = 2000
**p3 = 1000
***p3 = 10
Output
Value of a is 10
Value of a is 10
Value of a is 10
Value of a is 10
Address of a is 1000
Address of a is 1000
Address of p1 is 2000
Address of p2 is 3000
d. Pointer Arithmetic
Pointer variables can be used in expressions. We can add, subtract the integer using
pointer variables. It is also called as pointer expression.
Example
*c = *a + *b; *c = (*a) + (*b);
*a = *a + 5; or *a = (*a) + 5;
*p = *x * *b; *p = (*x) * (*b);
Write a C program to illustrate pointer arithmetic concept
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
int *pa,*pb,*pc;
clrscr();
printf("\nEnter 2 numbers:");
scanf("%d%d",&a,&b);
pa=&a;
pb=&b;
pc=&c;
*pc=*pa+*pb;
printf("\nSum=%d",*pc);
getch();
}
Output
Enter 2 numbers: 3 5
Sum = 8
Assignment
pa = &a[0];
Or
pa = a;
pa pa + 1 pa + 2 pa + 3 pa + 4 pa + 5
a
0 1 2 3 4 5
Pointer variable is incremented automatically for further initialization as shown above.
Example
0 1 2 3 4
A 10 20 30 40 50
4000 4002 4004 4006 4008
When pointer variable is incremented by 1, related base address will be incremented by (address
+ 2) because above declared type in an “integer”.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5]={10,20,30,40,50};
int i,*ptr[5]; //Pointer & array declaration
clrscr();
for(i=0;i<5;i++)
{
ptr[i]=&a[i]; //Initialization
}
for(i=0;i<5;i++)
{
printf("\nValue of a[%d] = %d",i,*ptr[i]);
}
getch();
}
Output
Value of a[0] = 10
Value of a[1] = 20
Value of a[2] = 30
Value of a[3] = 40
Value of a[4] = 50
Write a C program to perform arithmetic operations of two numbers using pointer and
functions
#include<stdio.h>
#include<conio.h>
void add(int *,int *);
void sub(int *,int *);
void mul(int *,int *);
void main()
{
int a,b,choice;
clrscr();
printf("\nEnter 2 numbers:");
scanf("%d%d",&a,&b);
printf("1.Addition\n2.Subtraction\n3.Multiplication\n");
printf("Enter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
add(&a,&b);
break;
case 2:
sub(&a,&b);
break;
case 3:
mul(&a,&b);
break;
default:
printf("Enter correct choice");
break;
}
getch();
}
void add(int *a,int *b)
{
int *add;
*add=*a+*b;
printf("\nSum=%d",*add);
}
void sub(int *a,int *b)
{
int *sub;
*sub=*a-*b;
printf("\nSubtraction=%d",*sub);
}
void mul(int *a,int *b)
{
int *mul;
*mul=*a**b;
printf("\nMultiplication=%d",*mul);
}
Output
Enter 2 numbers: 5 6
1.Addition
2.Subtraction
3.Multiplication
Enter your choice: 1
Sum=11
Enter 2 numbers: 5 6
Enter your choice: 2
Subtraction=-1
Enter 2 numbers: 5 6
Enter your choice: 3
Multiplication=30
Advantage of Pointer
1. Pointers are most efficient in handling arrays and functions.
2. Pointer allows dynamic memory management.
3. A pointer reduces length and complexity of program.
4. Pointer increases the execution speed and reduces the program execution time.
5. Pointer provide an efficient tool for manipulation dynamic data structure such as stack,
queue, linked lists, structures etc.,
STRUCTURE
An array is collection of similar data type. But user cannot fulfill all needs with same data
type. For example, if users want to collect student data base, he/she need to collect following
data roll number (integer), name (character), mark (float) etc. In such situation user cannot use
array data type alone. Hence collection of different data type is needed.
Structure is a derived data type. Structure is used to collect dissimilar data type. It is used
to collect different data type under common name. Structure is declared using ‘struct’ keyword.
Syntax
struct structure_name
{
structure members;
......
}object;
Here,
struct keyword
object it is used to access the members of the structure.
Example
struct student
{
int roll;
char name[20];
float mark;
}stu;
Structures members cannot be accessed directly. It can be accessed using its object with dot ( . )
operator as follows.
stu.roll;
stu.name;
stu.mark;
Defining a Structure
A Structure can be defined as follows
struct identifier
{
datatype member 1;
datatype member 2;
......
......
datatype member n;
};
where, struct is a keyword, identifier is a name that identifies structures. Member 1,
Member 2 ..... Members n are individual member declarations.
Declaring a Structure
A structure declaration is similar to the declaration of variables of any other data type. It
includes the following statements
1. Keyword “struct”
2. Structure name
3. List of members separated by semicolon
4. Objects to access members of structure
5. Terminating symbol
Example
struct book
{
int book_id;
char title[20];
char author[20];
float price;
}b1,b2;
where, struct is a keyword, book is a name that identifies structures. book_id, title, author
and price are individual member of structure. b1 & b2 are objects to access members of structure.
Example
b1.book_id; b2.book_id;
b1.title; b2.title;
b1.author; b2.author;
b1.price b2.price
name 5 Bytes
float 4 Bytes
Example1:
struct student
{
int roll;
char name[5];
float mark;
}stu={5, Tamil, 97.5};
Example2
struct book
{
int book_id;
char title[20];
char author[20];
float price;
};
struct book b1={100, “Computer Programming”, “Tamil”, 350.00};
struct book b1={210, “Computer Practice Lab”, “Selva”, 300.00};
Output
Enter student details
Roll Number : 6 Name : Tamil Mark : 97.5
emp.doj.day;
emp.doj.month;
emp.doj.year
emp.doj.day,emp.doj.month,emp.doj.year);
getch();
}
Output
Enter Employee details
ID: 12
Name: Tamil
Date of Joining: 27 June 2007
Employee details are:
ID Name Date of joining
12 Tamil 27 June 2007
Union:
It is a special data type available in C that allows storing different data types in the same
memory location. You can define a union with many members, but only one member can contain
a value at any given time. Unions provide an efficient way of using the same memory location
for multiple purposes.
Syntax:
union [union name]
{
member definition;
member definition;
...
member definition;
}union variable declaration;
union Data {
int i;
float f;
char str[20];
} data;
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;
}
Output:
Memory size occupied by data : 20
FILES
File is defined as a set of records that can be accessed through various file functions. In
order to store information permanently and retrieve it we need to use files. To use files we have
to learn about how to write information to a file and how to read information from a file.
Basically there are two types of files in the C:
Sequential files: The data will be stored or read sequentially.
Random access files: Data will be accessed and processed randomly.
File operations
i. File create and file open
ii. File read and File write
iii. File close
iv. File positioning functions
v. File error handling functions
i. File create and File open:
A file must be opened before performing any input or output operations.
Syntax
Keyword
Example:
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int rno;
char name[15] ;
FILE *fp1, *fp2;
fp1=fopen(“input.txt”, “r”);
fp2=fopen(“output.txt”, “w”);
while(!feof(fp1))
{
fscanf(fp1, “%d%s”, &rno, name);
fprintf(fp1, “%d\t%s\n”, &rno, name);
}
fclose(fp1);
fclose(fp2);
}
OUTPUT
Input File (Input.txt)
1001 kavi
1002 tamil
1003 sathya
Output File (Output.txt)
1001 kavi
1002 tamil
1003 sathya
fseek(fp1, 10, 1) The fpointer moves 10 bytes from the current position.
var = ftell(fptr);
Example:
n = ftell(fp1);
c. rewind() It is used to move the file pointer to the beginning of the file.
Syntax:
rewind(fp)
Example:
rewind(fp1)
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp1;
clrscr();
fp1=fopen("inputfile.txt","r");
if(fp1!=NULL)
{
printf("\nThe file pointer is at location:%d",ftell(fp1));
fseek(fp1,13,0);
printf("\nThe file pointer is at location:%d",ftell(fp1));
fseek(fp1,4,1);
printf("\nThe file pointer is at location:%d",ftell(fp1));
fseek(fp1,0,2);
printf("\nThe file pointer is at location:%d",ftell(fp1));
fseek(fp1,-10,2);
printf("\nThe file pointer is at location:%d",ftell(fp1));
rewind(fp1);
printf("\nThe file pointer is at location:%d",ftell(fp1));
}
getch();
}
Input File
Random File Access
OUTPUT
The file pointer is at location: 0
The file pointer is at location: 13
The file pointer is at location: 17
The file pointer is at location: 18
The file pointer is at location: 8
The file pointer is at location: 0
In sequential file access file contents are accessed sequential order i.e., one after another.
In sequential file, data are kept sequential. For example if user wants to access the forty
fourth record, first forty three records should be read sequentially to reach the forty fourth
record.
It takes more time
Example: Tape Drive, Magnetic Tape
Features
Advantage
Disadvantage
Records can be read only sequentially, if user want to access 50 th record, then first 49
records must be read.
Sequential file access does not support update operation.
Cannot be used for interactive applications.
Random Access File
In the random access file, the data can be accessed and processed randomly i.e in this
case the forty fourth record can be accessed directly. It takes less time than the sequential
file.
1. 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.
The malloc() function allocates single block of requested memory.
It doesn't initialize memory at execution time, so it has garbage value initially.
It returns NULL if memory is not sufficient.
Syntax
ptr=(cast-type*)malloc(byte-size)
Example
ptr = (int*) malloc(10 * sizeof(int));
This statement will allocate 20 bytes according to size of int (2 bytes) and the pointer
points to the address of first byte of memory.
Program
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int n,i,*ptr,sum=0;
clrscr();
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
getch();
}
OUTPUT
Enter number of elements: 3
Enter elements of array: 1 2 4
Sum=7
2. calloc()
#include<conio.h>
#include<stdlib.h>
void main()
{
int n,i,*ptr,sum=0;
clrscr();
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
getch();
}
OUTPUT
Enter number of elements: 3
Enter elements of array: 1 2 4
Sum=7
3. realloc()
If memory is not sufficient for malloc() or calloc(), user can reallocate the memory by
realloc() function. In short, it changes the memory size.
Syntax
ptr=realloc(ptr, new-size)
4. free()
The memory occupied by malloc() or calloc() functions must be released by calling free()
function. Otherwise, it will consume memory until program exit.
Syntax
free(ptr)
Difference between malloc() and calloc() functions in C:
malloc() calloc()
It allocates multiple blocks of requested
It allocates only single block of requested memory
memory
int *ptr;Ptr = calloc( 20, 20 * sizeof(int) );
int *ptr;ptr = malloc( 20 * sizeof(int) );
For the above, 20 blocks of memory will be
For the above, 20*4 bytes of memory only allocated
created and each contains 20*4 bytes of
in one block.
memory.
Total = 80 bytes
Total = 1600 bytes
malloc () doesn’t initializes the allocated memory. calloc () initializes the allocated memory to
It contains garbage values zero