BCA C Program UNIT-V
BCA C Program UNIT-V
Pointers
One of the powerful features of ‘C’ is its ability to access the memory
variables by their memory address. This can be achieved through a special type of
variable called pointer.
Ex: int i=3, this declaration creates memory for variable ‘i’ as shown below.
i Location name
3 value at location
The & is the address operator, it represents the address of the variable. This
operator returns the memory address of variable on which it is operated.
Ex: p=&a;
This statement assigns address of the variable ‘a’ to pointer variable ‘p’.
‘*’ 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.
This statement displays the data value stored at the address in ‘p’. The * is also used
to declare pointer variable.
In ‘C’ a pointer variable is declared by preceding its name with an asterisk ‘*’.
* indicates that the variable is a pointer variable. Holds the address of type
data type.
This declares the variable ‘p’ as a pointer variable that points to an integer
data type.
Initialisation of Pointers:
Once a pointer variable has been declared, it can be made point to a variable
using an assignment statement.
Ex: int a;
int *p;
p=&a;
This statements assigns address of variable ‘a’ to integer pointer ‘p’.
printf(“\n%d\t%d”, a, * int_ptr);
printf(“\n%f\t%f”, b, * float_ptr);
printf(“\n%c\t%c”, c, * char_ptr);
getch();
}
This programs gives the following output
25 25
35.95 35.95
/ /
#include “stdio.h”
main()
{
int i1, i2;
int *p1, p2;
i1=5;
p1=&i1;
i2=*p1/2+10;
p2=p1;
printf(“i1=%d, i2=%d, *p1=%d, *p2=%d”, i1,i2,*p1,*p2);
getch();
}
Operations on Pointers: The size of the data type to which the pointer variable
refers is the number of bytes of memory accessed when the pointer variable is
dereferenced by using the ‘*’ operator. The size of a pointer variable remains the
same irrespective of the data type to which it is pointing.
The computer uses memory for storing the instructions of program and also
for storing the values of the variables in the program
Ex : If we declare a variable called ‘count’ of type int, the system assigns locations in
memory to held the value of ‘count’.
As int_ptr is of type pointer to int, the value stored in the memory given by
*int_ptr is interpreted as an integer by the system.
The *int_ptr refers the value in the address of int_ptr i.e. the value of the
variable ‘count’.
Pointers and Structures
This statement declares a variable todaysdate of type struct date. A Pointer variable
can be defined as
struct date *dateptr;
dateptr = & todaysdate; will set the address of structure ‘todaysdate’ to
‘dateptr’.
Operator :
The structure pointer operator which is the dash followed by the greater
than sign, is used to access structure elements using pointer.
dateptr
. day 25
. month 1
. year 2019
# include “stdio.h”
main ()
{
struct emp
{
int eno;
char ename[20];
int deptno;
};
struct emp e;
struct emp *ptr;
ptr=&e;
printf(“\n Enter employee No:”);
scanf(“%d”, &e.eno);
printf(“\n Enter employee Name:”);
scanf(“%s”, &e.ename);
printf(“\n Enter Department No:”);
scanf(“%d”, &e.deptno);
printf(“\n Employee details \n”);
printf(“\n Employee No:%d”, ptreno);
printf(“\n Employee Name :%s”, ptrename);
printf(“\n Department No:%d”, ptrdeptno);
}
In the above program ptr is a pointer to structure ‘e’ of type struct emp. The
structure elements can be refered in both ways like e.eno, e.ename, e.deptno and
ptreno, ptrename, ptrdeptno.
Ex : struct intptrs
{
int *p1;
int *p2;
};
A structure called ‘intptrs’ is defined to contain two integer pointers, the first
one called p1 and second one p2.
# include “stdio.h”
main()
{
struct intptrs
{
int *p1;
int * p2;
};
#include “stdio.h”
main()
{
int first, second;
first=100;
second=200;
swap(first, second);
printf(“value of first =%d\t value of second =%d\n”, first, second);
getch();
}
swap(int a, int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
since in this program, the parameters are passed to function swap() using call by
value, function swap() can not interchange the values first, second of main()
function.
O/p is value of first=100 value of second = 200
Ex: call-by-reference
#include “stdio.h”
main()
{
int first, second;
first=100;
second=200;
swap(&first, &second);
printf(“The value of first=%d\t The value of second =%d\n”, first, second);
getch();
}
swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Since in this program, the parameters are passed to function swap() using call by
reference, function swap() interchanges the data values.
O/p The value of first = 200 The value of second = 100
int (*fnptr)(void)
main ()
{
int a;
fnptr = f1;
a=fnptr();
printf(“\n a=%d”, a);
getch();
}
int f1 (void)
{
int b=10;
return (b);
}
In the program fnptr=f1; assigns address of function f1() to fnptr pointer.
a=fnptr(); calls the function f1() and returns an integer value.
Pointers and Arrays
Arrays can be accessed using pointers. Pointers to arrays uses less memory
and executes faster.
Consider an array ‘value’ of 100 integers.
int value [100];
We can define a pointer variable to access array elements as
int *ptr;
------
value [10] value [1] value [2] value [99]
ptr
The statement
ptr=value; (or)
ptr=&value [0];
Will assign array address i.e. address of first element to ptr. By using
increment operator we can access all elements of an array
Ex : Following example explains accessing of array elements using pointers :
# include “stdio.h”
main ()
{
int a[10], i;
int *p;
p=a; (or) p=&a[0];
printf(“\n Enter Array Elements :”);
for (i=0; i<10;i++)
scanf(“%d”, &a[i]);
for (i=0; i<10;i++,p++)
printf(“\t%d”,*p);
}
getch();
}
p=a statement assigns address of array i.e. first element address to variable
‘p’. The statement ‘p++’ in loop points to subsequent elements in the array.
day [0] S U N D A Y \O
day [1] M O N D A Y \O
day [2] T U E S D A Y \O
day [3] W E D N E S D A Y \O
day [4] T H U R S D A Y \O
day [5] F R I D A Y \O
day [6] S A T U R D A Y \O
main ()
{
chat *name [10];
int i;
printf(“\n Enter Strings :\n”);
for (i=0; i<10;i++)
scanf (“%s” name[i]);
printf(“\n Entered Strings :\n)”;
for (i=0; i<10;i++)
printf(“\n%s”, name[i]);
getch();
}
In above example char *name [10]; statement can point to 10 strings. The
character strings is assigned and displayed using for loops.
8. With the address known, data can be accessed from anywhere in the
program.
9. Pointer to pointer concept is possible.
10. ‘Pointer’ is a powerful tool for ‘C’ programmers in software development.
Drawbacks of pointers:
NULL pointers
The word "NULL" is a constant in C language and its value is 0.
If any pointer does not contain any valid memory address or any pointer is
uninitialized, known as "NULL pointer".
Ex:
int a=10;
int *ptr1=&a;
int *ptr2;
int *ptr3=0;
Since C is a structured language, it has some fixed rules for programming. In ‘C’
memory will allocates for different data structures, variables and constants based on
their type.
The above declaration length of the array is 10. If we use 5 elements only, space for
other 5 elements is unutilized.
In other case if we need more than 10 elements, we need to change the array
definition.
1. malloc()
2. calloc()
3. free()
4. realloc()
calloc(): This function is used to dynamically allocate the specified number of blocks
of memory of the specified type. It initializes each block with a default value ‘0’.
This statement allocate contiguous space in memory for 25 elements each with the
size of float.
Ex: free(ptr);
Files
Introduction to Files:
File:
Both read and write file operations can be easily performed under many
operating systems. If we want to write program results into a file, then command.
prog > data, will execute the program with the name ‘prog’ and writes the output
to the file called data.
Ex : reverse <file1
This command takes the value from file ‘file1’ and redirects to program called
‘reverse’.
We can redirect input and output to the program at the same time.
Ex : reverse < number > data
This command reads all the input for the program ‘reverse’ from file ‘number’
and write all the output to the file ‘data’.
1. Opening File
2. Processing a File
3. Closing a File
Defining file Pointer :
A file is opened, accessed, closed through a file pointer. A file pointer is declared
using ‘FILE’, which is defined in <stdio.h>.
Ex : FILE * fp;
Modes :
‘w’ mode This mode opens the file in write mode. Only file write is possible
‘r’ mode This mode opens the file in read mode. Only file read is possible
‘a’ mode This mode opens the file in append mode. In this mode data is
added
from the end of the existing data.
If we add ‘b’ i.e ‘wb’, ‘rb’ etc., the file will be opened in binary mode for
corresponding system operation.
Ex : fp =fopen(“student.dat”, “w”);
This statement opens a file “student.dat” in write mode and return the file address
into file pointer ‘fp’.
The fopen() function opens the file, but if file is not existing the function creates a
file.
When operations are completed on a file, it is good habit to close the file. When a
program terminates normally, the system automatically closes any open files. It is
generally better programming practice to close a file, as soon as we are done with it.
fclose() function is used to close an opened file.
fclose (filepointer);
Ex : fclose (fp);
putc() :
The putc() function outputs one character to the file stream represented by the
specified file pointer. The syntax of putc() is :
The fprintf () is like printf ( ) except that this function writes the data to a
specified file. This function takes an additional parameter, which is the FILE pointer
that identifies the file to which data is to be written.
This statement writes the specified string into a file identified by the file pointer
fp.
fputs() function is used to write a string on to the file. The syntax of the fputs()
frunction is :
fputs() function writes the contents of the string pointed to by ‘str’ to the specified
stream. The null terminator is not written.
Ex: fputs(str, fp);
This statement writes the string ‘str’ in to the file pointed by the file pointer fp.
fwrite() : This function is used to write a record (or) structure to the file.
fwrite(&s, sizeof(structure),1,fp);
# include “stdio.h”
main ()
{
FILE *fp;
int n;
char str[5];
printf(“\n Enter No.of Strings :”);
scanf(“%d”, &n);
fp =fopen(“Names.dat”, “w”);
Ex:- 2
main()
{
FILE *fp;
struct student
{
int sno;
char sname[20];
float marks;
};
int n;
struct student s;
fp=fopen(“ student.dat”,”w”);
printf(“Enter No. of students:”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
scanf(“%d”,&s.sno);
gets(s.sname);
scanf(“%f”,&s.marks);
fwrite(&s,sizeof(struct student),1,fp);
}
fclose(fp);
}
getc() :
The getc() function inputs one character from a specified file stream. The syntax
of getc() is :
Ex : char flag ;
flag = get c (fp);
This function is used to read data from a file. The general format is
This statement reads an integer and float value assigns them to variables ‘a’ and
‘b’ respectively from a file identified by ‘fp’.
fread() : This function is used to read a record / structure from the file.
fread(&s, sizeof(structure),1,fp);
Ex:- 1
main()
{
FILE *fp;
char str[5];
fp = fopen (“names.dat”, “r”);
while (!feof(fp))
{
fgets(str, 5, fp);
prints(“\n%s”, str);
}
fclose (fp);
}
Ex:- 2
main()
{
FILE *fp;
struct student
{
int sno;
char sname[20];
float marks;
};
int n;
struct student s;
fp=fopen(“ student.dat”,”r”);
printf(“Enter No. of students:”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
fread(&s,sizeof(struct student),1,fp);
printf(“\n sno : %d”,s.sno);
printf(“\n sname : %s,s.sname);
printf(“\nmarks:%f”,s.marks);
}
fclose(fp);
}
Ex : while (! feof(fp))
{
.....
.....
}
The loop continues till end of the file.
Error Handling during File Operations
C language does not provide any direct support for error handling. However a few
methods and variables defined in error.h header file can be used to point out error
using the return statement in a function. In C language, a function returns -1 or
NULL value in case of any error and a global variable errno is set with the error
code. So the return value can be used to check error while program.
Errno:
Whenever a function call is made in C language, a variable named errno is
associated with it. It is a global variable, which can be used to identify which type of
error was encountered while function execution, based on its value. Below we have
the list of Error numbers and what do they mean.
C language uses the following functions to represent error messages associated with
errno:
perror(): returns the string passed to it along with the textual represention of
the current errno value.
strerror() is defined in string.h library. This method returns a pointer to the
string representation of the current errno value.
By default, the stdin, stdout, stderr refer to user’s console. This means that
whenever a program expects input from the standard input, it receives that input from
stdin. A program that writes to the standard output prints it data to stdout. Any error
messages that are generated by the library routines are sent to stderr.
ftell () : This function is used to locate the position of the file pointer. It returns a
long integer.
Ex : Long int L;
L=ftell (fp);
fseek() : This function is used to set the file pointer to the desired position.
rewind() : This function sets the file pointer to the initial position of the file.
Ex : rewind(fp).
Ex : remove (“tempfile”);
#include <stdio.h>
main ()
{
FILE *fp1, *fp2;
char flag;
fp1 = fopen (“Charadata1.data”, “r”);
fp2 = fopen (“Charadata2.data”, “w”);
while (! feof(fp))
{
flag = getc (fp1);
putc (flag, fp2);
}
fclose (fp1);
fclose (fp2);
getch();
}
In order to run above program the file chardata1.data should exists i.e. it should
be created. The while loop copies the contents of file chardata1.data to chardata2.data.
A header file is a file with extension .h which contains C function declarations and
macro definitions and to be shared between several source files. There are two types
of header files: the files that the programmer writes and the files that come with
compiler.
We request the use of a header file in our program by including it, with the C pre
processing directive #include.
Including a header file is equal to copying the content of the header file but we do
not do it because it will be very much error-prone and it is not a good idea to copy
the content of headerfile in the source files, specially if we have multiple source file
comprising our program.
A simple practice in C program is that we keep all the constants, macros, system
wide global variables, and function prototypes in header files and include that
header file wherever it is required.