Unit - V Pointers, Structures & Unions, Files: M.Srinivasa Rao, Ass - Prof, CSE Department
Unit - V Pointers, Structures & Unions, Files: M.Srinivasa Rao, Ass - Prof, CSE Department
Unit - V Pointers, Structures & Unions, Files: M.Srinivasa Rao, Ass - Prof, CSE Department
ADDRESS IN C:
If you have a variable ‘var’ in your program, ‘&var’ will give you its address in the memory,
where & is commonly called the reference operator.
This notation is seen in the scanf function. It is used in the function to store the user inputted
value in the address of var.
scanf("%d", &var);
Program:
#include <stdio.h>
int main()
{
int var = 5;
printf("Value: %d\n", var);
printf("Address: %u", &var); //Notice, the ampersand(&) before var.
return 0;
}
Output:
Value: 5
Address: 2686778
POINTERS:
A pointer is a variable whose value is the address of another variable, i.e., direct address of the
memory location. Like any variable or constant, you must declare a pointer before using it to
store any variable address.
Declaration:
Syntax: data_type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the nameof
the pointer variable.
Examples:
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
In the above example we have a pointer variable (*ptr) and a simple integer variable (var). We
have to assign the pointer variable to the address of ‘var’. It means that the pointer variable
‘*ptr’ now has the address of the variable ‘var’.
&is called reference operator which gives the address of a variable. Likewise, there is another
operator that gets you the value from the address, it is called a dereference operator (*).Note:
The * sign when declaring a pointer is not a dereference operator.
Program:
#include <stdio.h>
int main(){
int *pc;
int c;
c=22;
pc=&c;
printf("Address of pointer pc: %u\n",pc);
printf("Content of pointer pc: %d\n",*pc);
printf("Address of c: %u\n",&c);
printf("Value of c: %d\n",c);
return 0;
}
Output:
Output:
The value of ptr is 0
GENERIC POINTERS: It is a pointer variable that has void as its data type. It can be used
to point to variables of any type.
void *ptr;
In C, since we cannot have a variable of type void, the void pointer will therefore not point to
any data and thus cannot be dereferenced. We need to typecast a void pointer to another kind
of pointer before using it. It is often used when we want a pointer to point to data of different
types at different time.
#include <stdio.h>
int main () {
int x=10; void *ptr;
ptr = (int *)&x;
printf(“generic pointer points to the integer value %d”, *ptr);
return 0;
}
Output:
Generic pointer points to the integer value 10
#include <stdio.h>
void swap(int *n1, int *n2);
int main()
{
Output:
Number1 = 10
Number2 = 5
The address of memory location num1 and num2 are passed to the function swap and
the pointers *n1 and *n2 accept those values.
So, now the pointer n1 and n2 points to the address of num1 and num2 respectively.
When, the value of pointers are changed, the value in the pointed memory location also
changes correspondingly.
Hence, changes made to *n1 and *n2 are reflected in num1 and num2 in the main
function.
This technique is known as Call by Reference in C programming.
DANGLING POINTERS:
Dangling pointers arise when an object is deleted or de-allocated, without modifying
the value of the pointer, so that the pointer still points to the memory location of the de-
allocated memory.
In short pointer pointing to non-existing memory location is called dangling pointer.
Examples:
Way 1 : Using free or de-allocating memory
#include<stdlib.h>
{
char *ptr = malloc(Constant_Value);
.......
.......
free (ptr); /* ptr now becomes a dangling pointer */
}
After de-allocating memory, initialize pointer to NULL so that pointer will be no longer
dangling. Assigning NULL value means pointer is not pointing to any memory location
ADDRESS ARITHMETIC:
Address arithmetic is a method of calculating the address of an object with the help of
arithmetic operations on pointers and use of pointers in comparison operations. Address
arithmetic is also called pointer arithmetic.
We can perform arithmetic operations on the pointers like addition, subtraction, etc. However,
as we know that pointer contains the address, the result of an arithmetic operation performed
on the pointer will also be a pointer if the other operand is of type integer.
#include<stdio.h>
int main()
{
int number=50;
int *p;
p=&number;
printf("Address of p variable is %u \n",p);
p=p+1;
printf("After increment: Address of p variable is %u \n",p);
return 0;
}
POINTER TO POINTERS:
A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a
pointer contains the address of a variable. When we define a pointer to a pointer, the first
pointer contains the address of the second pointer, which points to the location that contains
the actual value as shown below.
Declaration:
int **var; //declares a pointer to pointer of type int
M.Srinivasa Rao, Ass.Prof, CSE department Page 5
When a target value is indirectly pointed to by a pointer to a pointer, accessing that value
requires that the asterisk operator be applied twice, as is shown below in the example:
Program:
#include <stdio.h>
int main () {
int var;
int *ptr;
int **pptr;
var = 3000;
ptr = &var; /* take the address of var */
pptr = &ptr; /* take the address of ptr using address of operator & */
printf("Value of var = %d\n", var ); /* take the value using pptr */
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);
return 0;
}
Output:
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000
When an array is declared, compiler allocates sufficient amount of memory to contain all the
elements of the array. Base address i.e address of the first element of the array is also allocated
by the compiler.
We can also declare a pointer of type int to point to the array arr.
int *p;
p = arr;
// or,
p = &arr[0]; //both the statements are equivalent.
In the above program, the pointer *p will print all the values stored in the array one by one. We
can also use the Base address (a in above case) to act as a pointer and print all the values.
The generalized form for using pointer with an array,
*(a+i)
is same as:
a[i]
ARRAY OF POINTERS:
Just like we can declare an array of int, float or char etc, we can also declare an array of
pointers, here is the syntax to do the same.
Syntax:
datatype *array_name[size];
Example:
int *arrop[5];
Here arrop is an array of 5 integer pointers. It means that this array can hold the address
of 5 integer variables, or in other words, you can assign 5 pointer variables of type pointer
to int to the elements of this array.
Program:
#include<stdio.h>
int main()
{
int a[5]={10,20,30,40,50};
int *b[5];
int i;
for(i=0;i<5;i++)
{
b[i]=&a[i];
printf(“Elements are :%d”, *b[i]);
}
Allocates requested size of bytes and returns a pointer to the first byte of
malloc()
allocated space
Allocates space for an array of elements, initializes them to zero and then returns
calloc()
a pointer to memory
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:
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.
Example:
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.
Program: to find sum of n elements entered by user using malloc() and free()
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, n,i;
printf("Enter number of elements: ");
scanf("%d", &n);
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:
ptr = (cast-type*)calloc(n, element-size);
This statement will allocate contiguous space in memory for an array of n elements.
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.
Program: to find sum of n elements entered by user using calloc() and free
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, n,i;
printf("Enter number of elements: ");
scanf("%d", &n);
free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed
on its own. You must explicitly use free() to release the space.
Syntax:
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
realloc()
If the previously allocated memory is insufficient or more than required, you can change the
previously allocated memory size using realloc().
Syntax:
ptr = realloc(ptr, newsize);
Here, ptr is reallocated with size of newsize.
Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, n,i;
printf("Enter number of elements: ");
scanf("%d", &n);
Output:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
STRUCTURES:
A structure is a user defined data type in C. A structure creates a data type that can be used to
group items of possibly different types into a single type
Example: Suppose you want to keep track of your books in a library. You might want to track
the following attributes about each book
Title
Author
Subject
Book ID
Syntax:
struct [structure tag]
{
member definition;
member definition;
...
member definition;
};
The structure tag is optional and each member definition is a normal variable definition, such as
int i; or float f; or any other valid variable definition. At the end of the structure's definition,
before the final semicolon, you can specify one or more structure variables but it is optional.
#include<stdio.h>
#include<conio.h>
struct Employee
{
int eno;
char ename[20];
float esalary;
};
void main()
{
struct Employee e={101,"Ravi",20000};
printf("Emp no: %d",e.eno);
printf("Emp name:%s",e.ename);
printf("Emp salary:%f",e.esalary);
getch();
}
Example:
#include<stdio.h>
#include<conio.h>
struct Employee
{
int eno;
char ename[20];
float esalary;
};
void main()
{
struct Employee e[5];
int i;
for(i=0;i<5;i++)
{
printf(“Enter Employee details”);
scanf("Emp no: %d",&e[i].eno);
scanf("Emp name:%s",e[i].ename);
scanf("Emp salary:%f",&e[i].esalary);
}
for(i=0;i<5;i++)
{
printf(“Enter Employee details”);
printf("Emp no: %d",e[i].eno);
printf("Emp name:%s",e[i].ename);
printf("Emp salary:%f",e[i].esalary);
}
getch();
}
POINTER TO STRUCUTRE:
#include<stdio.h>
#include<conio.h>
struct Employee
{
int eno;
char ename[20];
float esalary;
};
SELF-REFERENTIAL STRUCTURES:
Self-referential structures are those structures that have one or more pointers which
point to the same type of structure, as their member.
In other words, structures pointing to the same type of structures are self-referential in
nature.
A self-referential structure is used to create data structures like linked lists, stacks, etc.
Syntax:
struct struct_name
{
datatype datatypename;
struct_name *pointer_name;
};
10 20 30 40 X
ob1 ob2
Program:
#include <stdio.h>
struct node {
int data1;
char data2;
struct node* link;
};
int main()
{
Output:
30
40
UNIONS:
A union is a special data type available in C that allows to store 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-purpose.
Defining a Union:
To define a union, you must use the union statement in the same way as you did while defining a
structure. The union statement defines a new data type with more than one member for your
program.
Syntax:
union [union tag]
{
member definition;
member definition;
…….
member definition;
};
Example:
union Employee
{
int eno;
char name[20];
float salary;
};
To access any member of a union, we use the member access operator (.). The member access
operator is coded as a period between the union variable name and the union member that we
wish to access.
Program:
#include<stdio.h>
#include<conio.h>
union Employee
{
int eno;
char ename[20];
float esalary;
};
void main()
{
union Employee e={101,"Ravi",20000};
printf("Emp no: %d",e.eno);
printf("Emp name:%s",e.ename);
printf("Emp salary:%f",e.esalary);
getch();
}
FILES
In C programming, file is a place on your physical disk where information is stored.
Text files:
Text files are the normal .txt files that you can easily create using Notepad or any simple
text editors.
When you open those files, you'll see all the contents within the file as plain text. You
can easily edit or delete the contents.
They take minimum effort to maintain, are easily readable, and provide least security
and takes bigger storage space.
Binary files:
Binary files are mostly the .bin files in your computer.
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold higher amount of data, are not readable easily and provides a better
security than text files.
C provides a number of functions that helps to perform basic file operations. Following are
the functions,
Function description
fopen() create a new file or open a existing file
fclose() closes a file
getc() reads a character from a file
putc() writes a character to a file
fscanf() reads a set of data from a file
fprintf() writes a set of data to a file
getw() reads a integer from a file
putw() writes a integer to a file
fseek() set the position to desire point
ftell() gives current position in the file
rewind() s et the position to the begining point
FILE OPERATIONS:
In C, you can perform four major operations on the file, either text or binary:
Creating a new file
Opening an existing file
Closing a file
Reading from and writing information to a file
OPENING A FILE:
Opening a file is performed using the library function in the "stdio.h" header file: fopen().
Syntax:
fptr=fopen(“filename/path”, “mode”);
Examples:
fopen("E:\\cprogram\\newprogram.txt","w");
fopen("file1.txt","w");
Let's suppose the file newprogram.txt doesn't exist in the location E:\cprogram. The first
function creates a new file named newprogram.txt and opens it for writing as per the
mode 'w'.The writing mode allows you to create and edit (overwrite) the contents of the
file.
CLOSING A FILE:
The file (both text and binary) should be closed after reading/writing.Closing a file is
performed using library function fclose().
Syntax:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
fp=fopen("File1.txt","w");
printf("Enter data");
while((ch=getchar())!=EOF)
{
fputc(ch,fp);
}
fclose(fp);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
fp=fopen("File1.txt","r");
while((ch=fgetc(fp))!=EOF)
{
printf(“%c”,ch);
}
fclose(fp);
getch();
}
Example3:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
fp=fopen("File1.txt","a");
printf("Enter data");
while((ch=getchar())!=EOF)
{
fputc(ch,fp);
}
fclose(fp);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
int lines=0,characters=0;
fp=fopen("File1.txt","r");
while((ch=fgetc(fp))!=EOF)
{
printf(“%c”,ch);
characters++;
if(ch==’\n’)
{
lines++;
1. fseek()
2. ftell()
3. rewind()
1. fseek(): This function is used for seeking the pointer position in the file at the specified byte.
Pointer position:
This sets the pointer position in the file.
ftell():
This function returns the value of the current pointer position in the file.The value is count from the
beginning of the file.
Syntax: ftell(fptr);
Where fptr is a file pointer.
rewind():
This function is used to move the file pointer to the beginning of the given file.
Syntax: rewind( fptr); // Where fptr is a file pointer.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
int n;
fp=fopen("file1.c", "r");
n=ftell(fp);
printf(“Current position: %d”,n);
The typedef is a keyword used in C programming to provide some meaningful names to the
already existing variable in the C program. It behaves similarly as we define the alias for the
commands. In short, we can say that this keyword is used to redefine the name of an already
existing variable.
Syntax
In the above syntax, 'existing_name' is the name of an already existing variable while 'alias name' is
another name given to the existing variable.
Example:
void main()
{
typedef int cse;
cse a=5,b=6,c;
c=a+b;
printf("%d",c);
getch();
}
Enumeration (or enum) in C:
Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral
constants, the names make a program easy to read and maintain.
Example:
#include<stdio.h>
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
int main()
{
enum week day;
day = Wed;
printf("%d",day);
return 0;
}