Unit Ivqa
Unit Ivqa
UNIT–IV: Pointers: Pointers and Addresses, Pointers and function Arguments, Pointers and
arrays, Address Arithmetic, Character pointers and Functions, Pointer Arrays, Pointers to
Structures, Pointers to Pointers, Command Line Arguments.
Files: Introduction, Types of Files, File Access Functions, I/O on Files, Random Access to Files,
Error Handling.
UNIT-IV
1) What is pointer in c programming? What are its benefits?
Pointer is a user defined data type that creates special types of variables which can hold the address of
primitive data type like char, int, float, double or user defined data type like function, pointer etc. or
derived data type like array, structure, union, enum.
Examples:
int *ptr;
int (*ptr)();
int (*ptr)[2];
1. Value of variable.
2. Address of variable where it has stored in the memory.
1
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
About variable “ptr” :
4. Name of variable: ptr
5. Value of variable which it keeps: 1025
6. Address where it has stored in memory: 5000 (assume)
Pictorial representation:
Note: A variable where it will be stored in memory is decided by operating system. We cannot guess at
which location a particular variable will be stored in memory.
Pointers are built on three underlying concepts which are illustrated below:-
Memory addresses within a computer are referred to as pointer constants. We cannot change them. We
can only use them to store data values. They are like house numbers.
We cannot save the value of a memory address directly. We can only obtain the value through the
variable stored there using the address operator (&). The value thus obtained is known as pointer value.
The pointer value (i.e. the address of a variable) may change from one run of the program to another.
Once we have a pointer value, it can be stored into another variable. The variable that contains a pointer
value is called a pointer variable.
Pointers
//Declare a pointer
data_type_name * variable name
2
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
//Example
int *ptr;
The process of assigning the address of a variable to a pointer variable is known as initialization. Once a
pointer variable has been declared we can use assignment operator to initialize the variable.
Example program-1:
main( )
{
int a = 5 ;
printf ( "\nAddress of a = %u", &a );
printf ( "\nValue of a = %d", a );
};
address of a=1444
value of a=5
Look at the first printf( ) statement carefully. ‘&’ used in this statement is C’s ‘address of’ operator. The
expression &a returns the address of the variable a, which in this case happens to be 1444 .Hence it is
printed out using %u, which is a format specified for printing an unsigned integer.
The other pointer operator available in C is ‘*’, called ‘value at address’ operator. It gives the value
stored at a particular address. The ‘value at address’ operator is also called ‘indirection’ operator that is
shown in the program.
main()
{
int a = 5 ;
printf ( "\nAddress of a = %u", &a );
printf ( "\nValue of a = %d", a ) ;
printf ( "\nValue of a = %d", *( &a ) );
};
3
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
Address of a = 1444
Value of a = 5
Value of a = 5
Example Program-2:
#include <stdio.h>
int a, b;
int *p; /* Declaration of pointer variable */
int main(void)
{
a= 1;
b = 2;
p = &b; /* Initialization of pointer variable */
printf("\n");
printf("a has the value %d and is stored at %u\n", a, &a);
printf("b has the value %d and is stored at %u\n", b, &b);
printf("p has the value %d and is stored at %u\n", p, &p);
printf(" the value of the integer pointed to by p is %u\n", *p);
return 0;
};
The only requirement is that the variable “b” must be declared before the initialization takes place. This is
an initialization of p and not *p.
We must ensure that the pointer variables always point to the corresponding type of data.
4
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
Example :
float a,b;
int x,*p;
p=&a; /* wrong */
b=*p;
d) It is also possible to combine the declaration of data variable, the declaration of pointer variable and
the initialization of the pointer variable in one step.
Example :
int x, *p=&x;
is not valid because before the declaration of “x” , it’s address is being stored in pointer variable.
f) We could also declare a pointer variable with an initial value of NULL or 0(zero). That is, the
following statements are valid.
int *p = NULL;
int *p = 0;
4) a) Write a program to show pointer of any data type that occupies same space.
#include<stdio.h>
#include<conio.h>
void main()
clrscr();
getch();
5
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
OUTPUT:
4) b) Write a program to display the value of variable and its location-using pointer.
#include<stdio.h>
#include<conio.h>
void main()
int x=20;
int *pointer;
clrscr();
pointer=&x;
printf(“\nValue of x= %d”,*pointer);
getch();
OUTPUT:
Address of x=4060
Value of x=20
Address of pointer=4062
4) c) Write a program to add two numbers through variables and their pointers
#include<stdio.h>
6
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
#include<conio.h>
void main()
int x,y,z,p;
int *p1,*p2;
clrscr();
scanf(“%d %d”,&x,&y);
p1=&x;
p2=&y;
z=x+y;
p=*p1+*p2;
getch();
OUTPUT:
When we pass addresses to a function, the parameter receiving the addresses should be pointers. The
process of calling a function using pointers to pass the address of variables is known as “call by
reference”. The function which is called by reference can change the value of the variable used in the call.
Example :-
void main()
7
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
int x;
x=50;
printf(“%d\n”,x);
change(int *p)
*p=*p+10;
When the function change () is called, the address of the variable x, not its value, is passed into the
function change (). Inside change (), the variable p is declared as a pointer and therefore p is the address
of the variable x. The statement,
*p = *p + 10;
means “add 10 to the value stored at the address p”. Since p represents the address of x, the value of x is
changed from 20 to 30. Thus the output of the program will be 30, not 20.
Thus, call by reference provides a mechanism by which the function can change the stored values in the
calling function.
5)b) Write a ‘C’ function using pointers to exchange the values stored in two locations in the
memory.
Pointers can be used to pass addresses of variables to called functions, thus allowing the called
function to alter the values stored there.
Passing only the copy of values to the called function is known as "call by value".
Instead of passing the values of the variables to the called function, we pass their addresses, so
that the called function can change the values stored in the calling routine. This is known as "call
by reference", since we are referencing the variables.
Here the addresses of actual arguments in the calling function are copied into formal arguments
of the called function. Here The formal parameters should be declared as pointer variables to
store the address.
8
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
Functions return multiple values using pointers. The return type of function can be a pointer of type int ,
float ,char etc.
Example :
#include<stdio.h>
int * smallest(int * , int *);
void main()
{
int a,b,*s;
printf(“Enter a,b values “);
scanf(“%d%d”,&a,&b);
s=smallest(&a,&b);
printf(“smallest no. is %d”,*s);
}
int * smallest(int *a, int *b)
{
if(*a<*b)
return a;
else
return b;
}
In this example, “return a” implies the address of “a” is returned, not value .So in order to hold the
address, the function return type should be pointer.
9
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
6. Explain about various arithmetic operations that can be performed on pointers.
C language allows us to add integers to pointers and to subtract integers from pointers
Ex: If p1 ,p2 are two pointer variables then operations such as p1+4 , p2 - 2 , p1 - p2
can be performed.
We should not use pointer constants in division or multiplication. Also , two pointers cannot be
added.
Let us assume the address of p1 is 1002. After using p1=p1+1 , the value becomes 1004 but
not 1003.
Thus when we increment a pointer, its values is increased by length of data type that points to.
This length is called scale factor.
7. Explain in detail how to access a one dimensional array using pointers with an example
program?
When an array is declared the complier allocated a base address and sufficient amount of strong to
contain all the elements of the array in configous memory location the base address is the location of the
first element (index 0) of the array the complier also defines the array name as a constant to the first
element.
Suppose the base address of x is 1000 and amuming that each intger requires two types. The five elements
will be stored as follows.
value 12 3 4 5
10
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
the name x is defined as a constant pointer pointing to the first element, x[0], and therefore the value x is
1000, the location where x[0] is stored. That is
x=&x[0]=1000;
if we declare p as an intger pointer, then we can make the pointer p to the array x by the following
arigument
p=x;
now we can accen every value of x using p++ to move from one element to another, the relationshiop
between p and x is shown below
p=&x[0]=1000
p+1=&x[1]=1002
p+2=&x[2]=1004
p+3=&x[3]=1006
p+4=&x[4]=1008
Note:- address of an element in an array is calculated by its index and scale factor of the datatype
= 1000+(3*2)
= 1000+6
=1006
=2000+6*4
=2000+24
11
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
=2024.
Address of str[10]=2050+(10*1)
=2050+10
=2060.
Note2:- when handling arrays, of using array indexing we can use pointers to accen elements.
Program1:- write a program to access elements of array through different ways using pointers.//ptraryac.c
Solution:-
#include<stdio.h>
#include<conio.h>
void main()
int arr[5]={10,20,30,40,50};
int p=0;
clrscr();
printf("\n value@ arr[i] is arr[p] | *(arr+p)| *(p+arr) | p[arr] | located @address \n");
for(p=0;p<5;p++)
printf(" %d | ",arr[p]);
printf(" %d | ",*(arr+p));
12
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
printf(" %d | ",*(p+arr));
printf(" %d | ",p[arr]);
printf("address of arr[%d]=%u\n",p,arr[p]);
getch();
output:
8.Explain in detail how to access a two dimensional array using pointers with an example program?
*(x+i) or *(p+i), similar, any element in a 2-d array can be represented by the pointer as follows.
*(*(a+i)+j) or *(*(p+i)+j)
The base address of the array a is &a[0][0] and strating from here this address the complier contiguous
space for all the element row – wise
i,e the first element of the second row is placed immediately after the last element of the first row
and so on
int a[3][4]={{1,2,3,,4},{5,6,7,8},{9,10,11,12}};
13
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
The elements of a will be stored as shown below.
1 2 3 4 5 6 7 8 9 10 11 12
If we declare p as an int pointer with the intial address &a[0][0] then a[i][j] is equivalent to *(p+4xi+j)
you may notice if we increment I by 1, the p is incremented by 4, the size of each row making p element
a[2][3] is given by *(p+2x4+3) =*(p+11).
This is the reason why when a two –dimensional array is declared we must specify the size of the each
row so that the complier can determine the correct storage at mapping
Program:
#include<stdio.h>
void main()
int z[3][3]={{1,2,3},{4,5,6},{7,8,9}};
int i,j;
int *p;
clrscr();
p=&z[0][0];
for(i=0;i<3;i++)
for(j=0;j<3;j++)
14
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
for(i=0;i<9;i++)
printf("\n\t%d",*(p+i));
getch();
output:
String is array of characters terminated with a null character we can also use pointer to accen the
individual character in a string this is illustrated as below
Note :- in `c` a constant character string always represents a pointer to that string add the following
statement is valid
Char *name; // these stamen declare name as a pointer to character and to name the
constant character string “delhi”
15
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
program:
Program:
#include<stdio.h>
#include<conio.h>
void main()
int length=0;
char *name,*cptr;
name="sandhya STGY";
clrscr();
//gets(name);
puts(name);
cptr=name;
printf("\n\t%c is @ %u",*cptr,cptr);
cptr++; //when while loop ends cptr has the address of '\0' in it
16
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
printf("\n Length of string is:%d",length);
getch();
Output:
One important use of pointers is in handling of a table of string consider the following array string
Char name [3][25]; //that is name is table containing 3 names, each with a maximum length of 25
character
Instead of making each row a fixed number of character we can make it a pointer to a string of varying
length
“banana”
“pine apple”};
This declaration allocates only 21 bytes sufficient to hold all the character
17
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
To print all the 3 names this stamen is enough ,
*(name [i]+j)
Note:- The character arrays with the rows of varying length are called “ragged arrays’ and are better
handled pointers
10. What is an array of pointer? How it can be declared? Explain with an example?
We have studied array of different primitive data types such as int, float, char etc. Similarly C supports
array of pointers i.e. collection of addresses.
Example :-
#include<stdio.h>
#include<conio.h>
void main()
int *ap[3];
int al[3]={10,20,30};
int k;
for(k=0;k<3;k++)
ap[k]=al+k;
18
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
for(k=0;k<3;k++)
printf(“\t %u”,ap[k]);
printf(“\t %7d\n”,*(ap[k]));
Output:
Address Element
4060 10
4062 20
4064 30
In the above program , the addresses of elements are stored in an array and thus it represents array of
pointers.
A two-dimensional array can be represented using pointer to an array. But, a two-dimensional array can
be expressed in terms of array of pointers also. The conventional array definition is,
Where,
19
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
Note that exp2 is not used while defining array of pointers. Consider a two-dimensional vector initialized
with 3 rows and 4 columns as shown below,
int p[3][4]={{10,20,30,40},{50,60,70,80},{25,35,45,55}};
The elements of the matrix p are stored in memory row-wise (can be stored column-wise also) as shown
in Fig.
The elements of the matrix p are stored in memory row-wise (can be stored column-wise also) as shown
in Fig.
int *p[3];
Here, p is an array of pointers. P[0] gives the address of the first row, p[1] gives the address of the second
row and p[2] gives the address of the third row. Now, p[0]+0 gives the address of the element in 0th row
and 0th column, p[0]+1 gives the address of the elements in 0th row and 1st column and so on. In general,
11. How to use pointers to access structure? Write syntax and explain with example program.
Pointers to Structures:
Just as how a array name indicates a constant pointer to the array’s base address in the similar way a
structure variable also holds the base address of the structure.
20
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
suppose s is a variable of type struct for a structure student
struct student
char name[20];
int age;
char grade;
};
then
p->name;
p->age;
p->grade;
when ptr is incrtemented by one it is made to point toi the next record.
Program:
/* pointers to structures*/
#include<stdio.h>
#include<conio.h>
struct student
char name[20];
int age;
21
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
char grade;
};
void main()
clrscr();
//p=&s;
for(p=s;p<s+2;p++)
fflush(stdin);
scanf("%s %d %c",p->name,&p->age,&p->grade);
for(p=s;p<s+2;p++)
printf("\n %s %d %c",p->name,p->age,p->grade);
getch();
Output:
22
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
12. Write in detail about pointers to functions? Explain with example program.
Pointers to functions:-
A function, like a variable has a type and address location in the memory. It is therefore possible to
declare a pointer o A function, like a variable has a type and address location in the memory. It is
therefore possible to declare a pointer to a function which can then be used as an argument in another
function.
Type (*fptr)();
This tells the complier that fptr is a pointer to a function which returns type value the parentheses around
*fptr is necenary.
Because type *gptr(); would declare gptr as a function returning a pointer to type.
We can make a function pointer to point to a specific function by simply assigning the name of the
function to the pointer.
double (*p1)();
p1=mul();
It declares p1 as a pointer to a function and mul as a function and then make p1 to point to the function
mul.
To call the function mul we now use the pointer p1 with the list of parameters .
23
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
i,e (*p1)(x,y);//function call equivalent to mul(x,y);
Program:
#include<stdio.h>
#include<conio.h>
void main()
int x,y;
double (*p1)();
double res;
p1=mul;
clrscr();
scanf("%d %d",&x,&y);
res=(*p1)(x,y);
getch();
double val;
24
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
val=a*b;
return(val);
Output:
#include<stdio.h>
#include<conio.h>
double volume(double(*p1)(),int,int,int );
//int l,b;
void main()
int l,b,h;
double res;
clrscr();
scanf("%d %d %d",&l,&b,&h);
res= volume(area,l,b,h);
//printf("\n %d , %d , %d",l,b,h);
getch();
25
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
}
double val;
val=a*b;
return(val);
double vol;
vol=(*p1)(lb,wd);
vol*=ht;
return(vol);
output:
14. What is a pointer to pointer? Write syntax and explain with example program.
It is possible to make a pointer to point to another pointer variable. But the pointer must be of a type that
allows it to point to a pointer. A variable which contains the address of a pointer variable is known as
pointer to pointer. Its major application is in referring the elements of the two dimensional array.
26
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
Syntax for declaring pointer to pointer,
This declaration tells compiler to allocate a memory for the variable ‘q’ in which address of a pointer
variable which points to value of type data type can be stored.
q = & p;
This initialization tells the compiler that now ‘q’ points to the address of a pointer variable ‘p’.
** q;
Example:-
#include<stdio.h>
void main( )
27
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
int a=10;
p = &a;
ptr = &p;
clrscr( );
getch( );
Output:-
15. Explain the pointer size compatibility and dereferencing size compatibility with an example.
Size compatibility:
The size of all pointers is the same. Every pointer variable holds the address of one memory location in
the computer. But the size of variable that the pointer references is different, it depends on type( i.e sizes
are dependent on type and not its value).
Example program
#include<stdio.h>
void main(void)
char c;
char *pc;
int a;
int *pa;
28
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
Printf(“size of c: %d\n”,sizeof(c));
Printf(“size of a: %d\n”,sizeof(a));
Output: size of c: 1
size of pc : 2
size of starpc: 1
size of a: 2
size of pa : 2
size of starpa: 2
The dereference type is the type of the variable that the pointer is referencing, with one exception. It is
invalid to assign a pointer of one type to a pointer of another type, even though the values in both cases
are memory address and would therefore seem to be fully compatible.
Example:
char c;
int a;
char *pc;
int *pa;
pa=&a; //good
pa=&a;
29
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
16. Write a program for pointer to void?
We cannot assign a pointer of one type to other type. But, a pointer of any type can be assigned to pointer
to void type and a pointer to void type can be assigned to a pointer of any referenced type.
void *p;
int i;
float f;
p = &i;
#include<stdio.h>
Int main(void)
void *p;
int i=7;
float f=23.5;
p = &i;
p=&f;
getch();
Output: i contains: 7
30
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
f contains:23.500000
17. What are static and dynamic memory allocations? Differentiate between static and dynamic
memory allocation.
Memory can be reserved for the variables either during the compilation time or during execution time.
Memory can be allocated for variable using two different techniques:
1. Static allocation
2. Dynamic allocation
1) Static allocation: If the memory is allocated during compilation time itself, the allocation memory
space cannot be expanded to accommodate more data or cannot be reduced to accommodate less data.
In this techniques once the size of memory allocated is fixed it cannot be altered even during
execution time .this method of allocation memory during compilation time is called static memory
allocation.
2) Dynamic allocation: Dynamic memory allocation is the process of allocating memory during
execution time is called dynamic memory allocation. This allocation technique uses predefined function
to allocated and release memory for data during execution time.
It is the process of allocating memory at compile It is the process of allocating memory during
time. execution of program.
Fixed number of bytes will be allocated. Memory is allocated as and when it is needed.
The memory is allocated in memory stack. The memory is allocated from free memory
pool (heap).
Memory is allocated either in stack area or data Memory is allocated only in heap area
area
18. Explain about malloc( ) and calloc( ) dynamic memory management functions with an example.
31
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
The function malloc( ) allocates a block of size bytes from the free memory pool (heap).
It allows a program to allocate an exact amount of memory explicitly, as and when needed.
void *malloc (size_t size);
Argument: The parameter passed to malloc() is of the type size_t. This type is declared in the header file
stddef.h. size_t is equivalent to the unsigned int data type. Thus, in compilers where an int is 16 bits in
size, malloc() can allocate a maximum of 64KB at a time, since the maximum value of an unsigned int is
65535.
Return value:
On success, i.e., if free memory is available, malloc() returns a pointer to the newly allocated
memory. Usually, it is generic pointer. Hence, it should be typecast to appropriate data type
before using it to access the memory allocate.
On failure, i.e., if enough free memory does not exist for block, malloc() returns NULL. The
constant NULL is defined in stdio.h to have a value zero. Hence, it is safe to check the return
value.
Ex: 1) malloc(30); allocates 30 bytes of memory and returns the address of byte0.
calloc( ) provides access to the C memory heap, which is available for dynamic allocation of variable-
sized blocks of memory.
Arguments: Unlike malloc(), the function calloc( ) accepts two arguments: nitems and size. The parameter
nitems specifies the number of items to allocate and size specifies the size of each item.
Return value:
On success, i.e., if free memory is available, calloc( ) returns a pointer to the newly allocated
memory. Usually, it is generic pointer. Hence, it should be typecast to appropriate data type
before using it to access the memory allocated.
On failure, i.e., if enough free memory does not exist for block, calloc( ) returns NULL. The
constant NULL is defined in stdio.h to have a value zero. Hence, it is safe to verify the return
value before using it.
Ex: 1) calloc(3,5); allocates 15 bytes of memory and returns the address of byte0.
32
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
2) malloc(6,sizeof(float)); allocates 24 bytes of memory and returns the address of byte0.
19. Explain about free( ) and realloc( ) memory management allocations with an examples?
The function realloc() adjusts the amount of memory allocated to the block to size, copying the contents to
a new location if necessary.
Arguments: block is the pointer to the memory block that is previously obtained by calling malloc(),
calloc() or realloc(). If block is NULL pointer, realloc() works just like malloc().
Return value:
On success, this function returns the address of the reallocated block, which might be different
from the address of the original block.
On failure, i.e., if the block can’t be reallocated or if the size passed is 0, the function returns
NULL.
The function realloc() is more useful when the maximum size of allocated block can not be decided in
advance.
33
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
Argument: block is the pointer that is points to allocated memory by malloc( ), calloc( ) or realloc().
Passing an uninitialized pointer, or a pointer to a variable not allocated by malloc( ), calloc() or realloc()
could be dangerous and disastrous.
(or)
From this function definition, it is clear that the function main() takes these two arguments:
argc- an integer argument that holds the total number of arguments that are supplied at command prompt.
argv- a pointer to a character array or pointer-to-pointer-to character that holds all the strings (or
arguments) supplied at command prompt.
When we want to write a program that deals with command line arguments, do the following:
#include<stdio.h>
34
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
printf(“\n Number of arguments supplied=%d”,argc);
if(argc!=3)
exit(0);
for(i=0;i<argc;i++)
printf(“\t%s”,argv[i]);
Output:
$cc command.c
$./a.out apple boy cat dog //suggestion: (separate each string with space)
#include<stdio.h>
#include<stdlib.h>
int sum,i;
for(i=1,sum=0;i<argc;i++)
35
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
printf(“\n sum=%d”,sum);
Output:
$ cc sumnum.c
sum=154
FILES
Ans :
A file is an external collection of related data treated as a unit.
The primary purpose of a file is to keep record of data. Record is a group of related fields. Field is
a group of characters they convey meaning.
Files are stored in auxiliary or secondary storage devices. The two common forms of secondary
storage are disk (hard disk, CD and DVD) and tape.
Each file ends with an end of file (EOF) at a specified byte number, recorded in file structure.
A file must first be opened properly before it can be accessed for reading or writing. When a file
is opened an object (buffer) is created and a stream is associated with the object.
36
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
characters is processed in this kind of files. At one time, one character is processed and that too
sequentially. Either read a character or write a character operation is performed in these files. mode
specifies the purpose of opening a file
Different modes of opening a text file are
a) “r” : It opens the file for reading if it already exists otherwise returns error.
b) “w” : It the file already exists then it over write the content otherwise a file is
created for writing.
c) “a” : If the file exists, the file pointer points to end of file so that data can be
appended to file. If the file doesn’t exist then creates a new file and file
pointer points to beginning of file.
d) “r+” : The existing file is opened to the beginning for both reading and writing
e) “w+” : It is same as w except that it is opened for both reading and writing.
f) “a+” : It is same as a except that it is opened for both reading and writing.
NOTE: In a sequential access system, records are stored in a serial order and retrieved in the same order.
If a read operation is to be performed on the last record, then all the records before the last record need to
be read because of which a lot of time is wasted. It is achieved using functions like fprintf(), fscanf(),
getc(), putc(), etc.
2) Binary files or Random access files: Text mode is inefficient for storing large amount of numerical
data because it occupies large space. Only solution to this inefficient memory use is to open a file in
binary mode, which takes lesser space than the text mode. These files contain the set of bytes. Byte and
character are equivalent in c language hence a text file is no different than the binary file. In this case the
operations on the file can be sequence or random.
Different modes of opening a binary file are
rb The existing binary file is opened to the beginning for reading.
wb The existing binary file is opened to for writing.
ab The existing binary file is opened to the end for apending..
rb+ The existing binary file is opened to the beginning for both reading and writing.
wb+ Same as w except both for reading and writing.
ab+ Same as a except both for reading and writing.
37
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
NOTE: In random access file a particular part of a file can be accessed irrespective of other parts. It is
achieved using the functions like, fseek(), ftell(), and rewind() which are available in io library.
The read mode (r) opens an existing file for reading. When a file is opened in this mode, the file marker is
positioned at the beginning of the file (first character). The file marker is a logical element in the file
structure that keeps track of our current position in the file.
The file must already exist: if it does not, NULL is returned as an error. Files opened for reading are
shown in Figure 6.4. If we try to write a file opened in read mode, we get an error message.
The write mode (w) opens for writing. If the file doesn’t exist, it is created. IF it is already exists, it is
opened and all its data are erased; the file marker is positioned at the beginning of the file (first character)
It is an error to try to read from a file opened in write mode. A file opened for writing is shown in figure
6.4.
The append mode (a) also opens an existing for writing. Instead of creating a new file, however, the
writing starts after the last character; that is new data is added, or appended, at the end of the file.
IF the file doesn’t exist, it is created and opened. In this case, the writing will start at the beginning of the
file; File opened in append mode are shown in Figure 6.4.
In this mode file is opened for both reading and writing the data. If a file does not exist then NULL, is
returned.
38
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
Syntax: fp=fopen (“filename”,”r+”);
In this mode file is opened for both writing and reading the data. If a file already exists its contents erased.
If a file does not exist then new file created.
In this mode file is opened for reading the data as well as data can be added at the end.
39
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
Naming and opening a file:
A name is given to the file used to store data. The file name is a string of characters that make up a valid
file name for operating system. It contains two parts. An optional name and an optional period with
extension.
a) getc(); It is used to read characters from file that has been opened for read operation.
Syntax: C=gets (file pointer)
This statement reads a character from file pointed to by file pointer and assign to c.
It returns an end-of-file marker EOF, when end of file as been reached
b) fscanf();
This function is similar to that of scanf function except that it works on files.
Syntax: fscanf (fp, ”control string”, list);
Example fscanf(f1,”%s%d”,str,&num);
The above statement reads string type data and integer types data from file.
c) getw(); This function reads an integer from file.
Syntax: getw (file pointer);
d) fgets(): This function reads a string from a file pointed by a file pointer. It also copies the string to a
memory location referred by an array.
Syntax: fgets(string,no of bytes,filepointer);
e) fread(): This function is used for reading an entire structure block from a given file.
40
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
Syntax: fread(&struct_name,sizeof(struct_name),1,filepointer);
Closing a file:
A file is closed as soon as all operations on it have been completed.
Library function for closing a file is
fclose(file pointer);
Example: fclose(fp); This statement closes a file pointed by file pointer fp.
Or fcloseall(), to close all opened files at a time.
4. What are the file I/O functions in C. Give a brief note about the task performed by each function.
Ans:
In order to perform the file operations in C we must use the high level I/O
operation functions which are in C standard I/O library.
41
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
i)fopen():.The function fopen is one of the Standard Library functions and returns a file pointer which you use
to refer to the file you have opened e.g.
The above statement opens a file called prog.c for reading and associates the file pointer fp with the file.When
we wish to access this file for I/O, we use the file pointer variable fp to refer to it. You can have up to about 20
files open in your program - you need one file pointer for each file you intend to use.
ii)fclose():Closing a file ensures that all outstanding information associated with the file is flushed out
from the buffers and all links to the file are broken.
Another instance where we have to close a file is to reopen the same file in a different mode.
fclose (file_pointer);
42
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
Once a file is closed, its file pointer can be reused for another file.
.
iii) getc():
getc() is used to read a character from a file that has been opened in
a read mode.For example the statement
c=getc(fp);
would read a character from the file whose file pointer is fp. The file pointer moves by one character for
every operation of getc(). The getc() will return an end-of –marker EOF, when an end of file has been
reached.
In order to handle a group of mixed data simultaneously there are two functions that are fprintf() and
fscanf().These two functions are identical to printf and scanf fuctions,except they work on files. The first
argument of these functions is a file pointer which specifies the file to be used . the general form of fprintf
is
fprintf(fp,”control string”,list);
where fp is a file pointer associated with a file that has been opened for writing . the control string
contains output specifications for the items in the list. .
fprintf(fp,”%s %f %d”,name,6.6,age);
Like fprintf fscanf() also contains the same syntax which is used to read
a no of values from a file.
fscantf(fp,”control string”,list);
like scanf , fscanf also returns the number number of items that are
successfully read.when the end of file is it returns the value EOF.
43
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
vi) getw() &putw():
The getw() and putw() are integer oriented functions .They are similar to the getc() and putc()
functions and are used to read and write integer values . These functions would be useful when we deal
with only integer data. The general form of
putw(integer,fp);
getw(fp);
vii)ftell:-
ftell takes a file pointer and returns a number of type long, that
corresponds to the current position. This function is useful in saving the current
position of the file,which can be later used in the program.
Syntax:
N=ftell(fp);
N would give the Relative offset (In bytes) of the current position. This means that already n bytes have a
been read or written.
viii)rewind:-
It takes a file pointer and resets the position of to the start of the file.
Syntax:
rewind(fp);
n=ftell(fp);
would assign 0 to n because the file position has been set to start of the file by
rewind. The first byte in the file is numbered 0,second as 1, so on. This function
helps in reading the file more than once, with out having to close and open the file.
xi)fseek:-
fseek function is used to move the file pointer to a desired location in the
file.
Syntax:
44
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
fseek(file ptr,offset,position);
is a pointer to the file concerned, offset is a number or variable of type file pointers.long,and position is
an integer number. The offset specifies the number of
positions(Bytes) to be moved le from the location specified by the position.
b) ftell(): it returns the current position of the file ponter. it returns the pointer from the beginning of
file. Syntax: ftell(filepointer);
c) rewind(): this function resets the file pointer at the beginning of the file.
Syntax: rewind(filepointer);
5. Explain the command line arguments. What are the syntactic constructs followed in ‘C’.
Ans :
Command line argument is the parameter supplied to a program when the program is
invoked.This parameter may represent a file name the program should process. For example, if we want
to execute a program to copy the contents of a file named X_FILE to another one name Y_FILE then we
may use a command line like
c>program X_FILE Y_FILE
45
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
Program is the file name where the executable code of the program is stored. This eliminates the
need for the program to request the user to enter the file names during execution. The ‘main’ function can
take two arguments called argc, argv and information contained in the command line is passed on to the
program to these arguments, when ‘main’ is called up by the system. The variable argv is an argument
vector and represents an array of characters pointers that point to the command line arguments. argc is an
argument counter that counts the number of arguments on the command line. The size of this array is
equal to the value of argc. In order to access the command line arguments, we must declare the ‘main’
function and its parameters as follows:
main(argc,argv)
int argc;
char *arg[ ];
{
……….
……….
}
Example:- A program to copy the contents of one file into another? Or demonistrate command
line arguments
Void main(int argc,char* argv[]) /* command line arguments */
{
FILE *ft,*fs; /* file pointers declaration*/
Int c=0;
If(argc!=3)
Printf(“\n insufficient arguments”);
/* opening files*?
Fs=fopen(argv[1],”r”);
Ft=fopen(argv[2],”w”);
/*error handling*/
If (fs==NULL)
{
Printf(“\n source file opening error”);
46
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
Exit(1) ;
}
If (ft==NULL)
{
Printf(“\n target file opening error”);
Exit(1) ;
}
/*Reading file and writing into second file*/
While(!feof(fs))
{
Fputc(fgetc(fs),ft);
C++;
}
Printf(“\n bytes copied from %s file to %s file =%d”,argv[1].argv[2],c);
C=Fcloseall(); /*closing all files*/
Printf(“files closed=%d”,c);
}
a) feof(): the feof() function can be used to test for an end of file condition. It takes a FILE pointer as its
only argument and returns a nonzero integer value if all of the data from the specified file has been
47
Q&A for Previous Year Questions Subject: CPDS (B.Tech. I Year) Subject Code: GR11A1003
UNIT-IV
------------------------------------------------------------------------------------------------------------------------------------------
read, and returns zero otherwise. If fp is a pointer to file that has just opened for reading, then the
statement
if(feof(fp))
printf(“End of data”);
would display the message “End of data”. On reaching the end of file condition.
b) ferror(): The ferror() function reports the status of the file indicated. It also takes a FILE pointer as
its argument and returns a nonzero integer if an error has been deteched upto that point, during
processing. It returns zero otherwise. The statement
if(ferror(fp)!=0)
printf(“an error has occurred\n”);
c) we know that whenever a file is opened using fopen function, a file pointer is returned. If the file
cannot be opened for some reson, then the function returns a null pointer. This facility can be used to test
whether a file has been opened or not. Example
if(fp==NULL)
printf(“File could not be opened.\n”);
d) perror(): it is a standard library function which prints the error messages specified by the compiler
example: if(ferror(fp))
perror(filename);
48