Unit - 4
Unit - 4
Unit - 4
UNIT-4
Pointers
Definition:
Pointer is a variable that stores/hold address of another variable of same data type/ t is also known as
locator or indicator that points to an address of a value. A pointer is a derived data type in C
Pointer allows references to function and thereby helps in passing of function as arguments to
other function.
Declaration of Pointer
data_type* pointer_variable_name;
int* p;
Note: void type pointer works with all data types, but isn't used often.
Pointer Initialization is the process of assigning address of a variable to pointer variable. Pointer variable
contains address of variable of same data type
int a = 10 ;
1
int *ptr ; //pointer declaration
or,
float a;
int *ptr;
As you can see in the above figure, pointer variable stores the address of number variable i.e. fff4. The
value of number variable is 50. But the address of pointer variable p is aaa3.
By the help of * (indirection operator), we can print the value of pointer variable p.
& is called reference operator. It gives you the address of a variable. There is another operator that gets
you the value from the address, it is called a dereference operator (*).
2
Dereferencing of Pointer
Once a pointer has been assigned the address of a variable. To access the value of variable, pointer is
dereferenced, using the indirection operator *.
int a,*p;
a = 10;
p = &a;
Normal variable stores the value whereas pointer variable stores the address of the variable.
Always C pointer is initialized to null, i.e. int *p = null.The value of null pointer is 0.
Symbol is used to get the value of the variable that the pointer is pointing to.
Two pointers can be subtracted to know how many elements are available between these two
pointers.
Example:
#include <stdio.h>
#include <conio.h>
3
void main()
int number=50;
int *p;
clrscr();
getch();
Output
Value of p variable is 50
Example:
#include <stdio.h>
int main()
int *ptr, q;
q = 50;
ptr = &q;
printf("%d", *ptr);
4
return 0;
Output
50
Example:
#include <stdio.h>
int main()
int *p;
p= &var;
Output:
5
Value of var is: 10
NULL Pointer
A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't have any
address to be specified in the pointer at the time of declaration, you can assign NULL value.
Or
It is always a good practice to assign a NULL value to a pointer variable in case you do not have an exact
address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL
is called a null pointer.int *p=NULL;
Note: The NULL pointer is a constant with a value of zero defined in several standard libraries/ in most
the libraries, the value of pointer is 0 (zero)
Example:
Pointers to Pointers
Pointers can point to other pointers /pointer refers to the address of another pointer. Pointer can point to
the address of another pointer which points to the address of a value.
Example:
6
#include <stdio.h>
#include <conio.h>
void main(){
int number=50;
clrscr();
p2=&p;
getch();
Output
Value of *p variable is 50
When an array is declared, compiler allocates sufficient amount of memory to contain all the elements of
the array. Base address which gives location of the first element is also allocated by the compiler.
7
Assuming that the base address of arr is 1000 and each integer requires two byte, the five element will be
stored as follows
Here variable arr will give the base address, which is a constant pointer pointing to the element, arr[0].
Therefore arr is containing the address of arr[0] i.e 1000.
int arr[5]={ 1, 2, 3, 4, 5 };
int *p;
p = arr;
or
Now we can access every element of array arr using p++ to move from one element to another.
NOTE : You cannot decrement a pointer once incremented. p-- won't work.
Pointer to Array
we can use a pointer to point to an Array, and then we can use that pointer to access the array.
int i;
8
printf("%d", *p);
p++;
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 pointer and print all the values.
Consider an array:
int arr[4];
In C programming, name of the array always points to address of the first element of an array.
9
In the above example, arr and &arr[0] points to the address of the first element.
Since, the addresses of both are the same, the values of arr and &arr[0] are also the same.
Similarly,
Example: Program to find the sum of six numbers with arrays and pointers
#include <stdio.h>
int main()
int i, classes[6],sum = 0;
printf("Enter 6 numbers:\n");
scanf("%d",(classes + i));
return 0;
10
}
Output
Enter 6 numbers:
Sum = 21
Increment(++)
Decrement(--)
Addition(+)
Subtraction(-)
Increment pointer:
1. Incrementing Pointer is generally used in array because we have contiguous memory in array and we
know the contents of next memory location.
2. Incrementing Pointer Variable Depends Upon data type of the Pointer variable.
Address + 1 = Address
11
Address++ = Address
++Address = Address
Note:
32 bit
64 bit
Example:
#include <stdio.h>
void main()
int number=50;
12
int *p;//pointer to int
p=p+1;
Output
Decrement(--)
Example:
#include <stdio.h>
void main()
int number=50;
p=p-1;
Output
13
Address of p variable is 3214864300
Addition(+)
Note:
32 bit
64 bit
Example:
#include <stdio.h>
void main()
int number=50;
Output
14
Subtraction (-)
Like pointer addition, we can subtract a value from the pointer variable. The formula of subtracting value
from pointer variable.
Example:
#include <stdio.h>
void main()
int number=50;
Output
Array of Pointers
An array of pointers would be an array that holds memory locations. An array of pointers is an indexed set
of variables in which the variables are pointers (a reference to a location in memory).
Syntax:
Example
int *ptr[MAX];
15
Example1:
#include <stdio.h>
int main ()
int i, *ptr[MAX];
return 0;
16
}
Output
Value of var[0] = 10
Example2:
#include <stdio.h>
#include <conio.h>
main()
clrscr();
int *array[3];
int i;
array[0] = &x;
array[1] = &y;
array[2] = &z;
array[i]);
getch();
return 0;
Output
17
Structure Definition
Structure is a user defined data type which hold or store heterogeneous/different types data item
Or
Or
A structure is a collection of one or more data items of different data types, grouped together under a single
name.
Variables inside the structure are called members of structure. Each element of a structure is called a
member.
Struct keyword is used to define/create a structure. Struct define a new data type which is a Collection of
different type of data.
Syntax
data_type member1;
data_type member2;
data_type member n;
};
Example
18
struct employee
{ int id;
char name[50];
float salary;
};
Here, struct is the keyword, employee is the tag name of structure; id, name and salary are the members or
fields of the structure. Let's understand it by the diagram given below:
We can declare variable for the structure, so that we can access the member of structure easily.
2. By declaring variable at the time of defining structure/ Declaring Structure Variables with Structure
definition
1st way:
19
Let's see the example to declare structure variable by struct keyword. It should be declared
struct employee
int id;
char name[50];
float salary;
};
2nd way:
Let's see another way to declare variable at the time of defining structure.
struct employee
{ int id;
char name[50];
float salary;
}e1,e2;
But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare the structure
variable many times.
If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in main() function.
Structure Initialization
struct Patient
float height;
20
int weight;
int age;
};
or
p1.weight = 73;
p1.age = 23;
When the variable is normal type then go for struct to member operator.
When the variable is pointer type then go for pointer to member operator.
structure_variable_name.member_name
Example
struct book
char name[20];
char author[20];
int pages;
};
21
for accessing the structure members from the above example
Example
struct emp
int id;
char name[36];
int sal;
};
Example of Structure in C
#include<stdio.h>
#include<conio.h>
struct emp
int id;
char name[36];
float sal;
};
void main()
struct emp e;
clrscr();
scanf("%d",&e.id);
22
scanf("%s",&e.name);
scanf("%f",&e.sal);
printf("Id: %d",e.id);
printf("\nName: %s",e.name);
printf("\nSalary: %f",e.sal);
getch();
Output
Id : 05
Name: Spidy
Salary: 45000.00
Example
#include <stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
int main( )
e1.id=101;
23
printf( "employee 1 name : %s\n", e1.name);
return 0;
Output:
employee 1 id : 101
Arrays of Structures
Array of structures to store much information of different data types. Each element of the array representing
a structure variable. The array of structures is also known as collection of structures.
Ex : if you want to handle more records within one structure, we need not specify the number of structure
variable. Simply we can use array of structure variable to store them in one structure variable.
Example of structure with array that stores information of 5 students and prints it.
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct student{
int rollno;
char name[10];
24
};
void main(){
int i;
clrscr();
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
getch();
Output:
Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
25
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz
Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz
Example
#include <stdio.h>
#include <string.h>
struct student
int id;
char name[30];
float percentage;
};
int main()
int i;
26
struct student *ptr;
ptr = &record1;
return 0;
OUTPUT:
Records of STUDENT1:
Id is: 1
Self‐referential Structures
A structure consists of at least a pointer member pointing to the same structure is known as a self-referential
structure. A self referential structure is used to create data structures like linked lists, stacks, etc. Following
is an example of this kind of structure:
A self-referential structure is one of the data structures which refer to the pointer to (points) to another
structure of the same type. For example, a linked list is supposed to be a self-referential data structure. The
next node of a node is being pointed, which is of the same struct type. For
example,
type member1;
type membere2;
::
::
27
typeN memberN;
Ex:
struct emp
int code;
}
Unions
A union is a special data type available in C that allows to store different data types in the same memory
location.
Unions are conceptually similar to structures. The syntax of union is also similar to that of structure. The
only difference is in terms of storage. In structure each member has its own storage location, whereas all
members of union use a single shared memory location which is equal to the size of its largest data member.
We can access only one member of union at a time. We can’t access all member values at the same time in
union. But, structure can access all member values at the same time. This is because, Union allocates one
common storage space for all its members. Whereas Structure allocates storage space for all its members
separately.
28
syntax
union union_name
data_type member1;
data_type member2;
29
data_type memeberN;
};
Example
union employee
{ int id;
char name[50];
float salary;
};
Example
#include <stdio.h>
#include <string.h>
union Data
int i;
float f;
char str[20];
};
int main( )
data.i = 10;
data.f = 220.5;
30
printf( "data.f : %f\n", data.f);
return 0;
When the above code is compiled and executed, it produces the following result −
OUTPUT:
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Here, we can see that the values of i and f members of union got corrupted because the final value assigned
to the variable has occupied the memory location and this is the reason that the value of str member is
getting printed very well.
Now let's look into the same example once again where we will use one variable at a time which is the main
purpose of having unions.
#include <stdio.h>
#include <string.h>
union Data
int i;
float f;
char str[20];
};
int main( )
31
data.i = 10;
data.f = 220.5;
return 0;
When the above code is compiled and executed, it produces the following result −
OUTPUT:
data.i : 10
data.f : 220.500000
data.str : C Programming
Here, all the members are getting printed very well because one member is being used at a time.
32
Enumerations
An enum is a keyword, it is an user defined data type. All properties of integer are applied on Enumeration
data type so size of the enumerator data type is 2 byte. It work like the Integer.
It is used for creating an user defined data type of integer. Using enum we can create sequence of integer
constant value.
Syntax
In above syntax tagname is our own variable. tagname is any variable name.
33
It is start with 0 (zero) by default and value is incremented by 1 for the sequential identifiers in the list. If
constant one value is not initialized then by default sequence will be start from zero and next to generated
value should be previous constant value one.
Example of Enumeration in C
#include<stdio.h>
#include<conio.h>
void main()
int a;
clrscr();
a=x+y+z; //0+1+2
printf("Sum: %d",a);
getch();
Output
34
Sum: 3
Example of Enumeration in C
#include<stdio.h>
#include<conio.h>
void main()
today=tue;
printf("%d day",today+1);
getch();
Output
3 day
typedef
The typedef is a keyword that allows the programmer to create a new data type name for an existing data
type. So, the purpose of typedef is to redefine the name of an existing variable type.
Syntax
Example of typedef
#include<stdio.h>
#include<conio.h>
void main()
35
int a=10;
Integerdata b=20;
Integerdata s;
clrscr();
s=a+b;
getch();
Output
Sum: 20
The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at
runtime.
Or
The process of allocating memory at runtime is known as dynamic memory allocation. Library routines
known as "memory management functions" are used for allocating and freeing memory during execution
of a program. These functions are defined in stdlib.h.Dynamic memory allocation in c language is possible
by 4 functions of stdlib.h header file.
1. malloc()
2. calloc()
3. realloc()
4. free()
36
Note: Dynamic memory allocation related function can be applied for any data type that's why dynamic
memory allocation related functions return void*.
Global variables, static variables and program instructions get their memory in permanent storage area
whereas local variables are stored in area called Stack. The memory space between these two region is
known as Heap area. This region is used for dynamic memory allocation during execution of the program.
The size of heap keep changing.
malloc()
The malloc() function allocates single block of requested memory at runtime. This function reserves a block
of memory of given size and returns a pointer of type void. This means that we can assign it to any type of
pointer using typecasting. It doesn't initialize memory at execution time, so it has garbage value initially. If
it fails to locate enough space (memory) it returns a NULL pointer.
37
syntax
ptr=(cast-type*)malloc(byte-size)
Example
int *x;
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.
Example
#include <stdio.h>
#include <stdlib.h>
int main()
scanf("%d", &num);
if(ptr == NULL)
exit(0);
38
sum += *(ptr + i);
free(ptr);
return 0;
calloc()
Calloc() is another memory allocation function that is used for allocating memory at runtime. calloc
function is normally used for allocating memory to derived data types such as arrays and structures. The
calloc() function allocates multiple block of requested memory.It initially initialize (sets) all bytes to zero.If
it fails to locate enough space( memory) it returns a NULL pointer.
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.
Syntax
Example
int*arr;
cahr*str;
Example
struct employee
char *name;
39
int salary;
};
emp *e1;
e1 = (emp*)calloc(30,sizeof(emp));
Example
#include <stdio.h>
#include <stdlib.h>
int main()
scanf("%d", &num);
if(ptr == NULL)
exit(0);
40
printf("Sum = %d", sum);
free(ptr);
return 0;
Or
If the previously allocated memory is insufficient or more than required, you can change the previously
allocated memory size using realloc().
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In
short, it changes the memory size. By using realloc() we can create the memory dynamically at middle
stage. Generally by using realloc() we can reallocation the memory. Realloc() required 2 arguments of type
void*, size_type.
Void* will indicates previous block base address, size-type is data type size. Realloc() will creates the
memory in bytes format and initial value is garbage.
syntax
ptr=realloc(ptr, new-size)
Example
int *x;
x=(int*)malloc(50 * sizeof(int));
41
x=(int*)realloc(x,100); //allocated a new memory to variable x
Example
void*realloc(void*, size-type);
int *arr;
arr=(int*)calloc(5, sizeof(int));
.....
........
....
arr=(int*)realloc(arr,sizeof(int)*10);
Example:
#include <stdio.h>
#include <stdlib.h>
int main()
scanf("%d", &n1);
printf("%u\t",ptr + i);
scanf("%d", &n2);
42
printf("%u\t", ptr + i);
return 0;
free()
When your program comes out, operating system automatically release all the memory allocated by your
program but as a good practice when you are not in need of memory anymore then you should release that
memory by calling the function free().
The memory occupied by malloc() or calloc() functions must be released by calling free() function.
Otherwise, it will consume memory until program exit.
Or
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);
Example
#include <stdio.h>
#include <stdlib.h>
int main()
scanf("%d", &num);
if(ptr == NULL)
free(ptr);
return 0;
44