Unit 4
Unit 4
Unit IV
Pointer:
A pointer is a variable which holds memory address of another variable. Pointers are powerful tools that allow direct
memory access and manipula on.
Declaring Pointer:
Declara on of pointer variable is similar to the crea on of normal variable but the name is prefixed with *
symbol.
Syntax:
datatype *pointerName ;
Example:
int *ptr ;
In the above example declara on, the variable "ptr" is a pointer variable that can be used to store any integer
variable address.
To assign address to a pointer variable we use assignment operator with the following syntax.
Example:
ptr = &a ;
We use the symbol "*" in front of pointer variable name to access the value of variable to which the pointer
is poin ng.
Syntax:
*pointerVariableName
Example Code
#include<stdio.h>
int main()
{
int a = 10, *ptr ;
ptr = &a ;
printf("Address of variable a = %u\n", ptr) ;
printf("Value of variable a = %d\n", *ptr) ;
printf("Address of variable ptr = %u\n", &ptr) ;
return 0;
}
Output:
Value of variable a = 10
In c language, we use the reference operator "&" to access the address of variable.
For example, to access the address of a variable "marks" we use "&marks".
We use the following prin statement to display memory loca on address of variable "marks".
Example:
prin ("Address : %u", &marks) ;
In the above example statement %u is used to display address of marks variable.
Address of any memory loca on is unsigned integer value.
A pointer variable to store the address of another pointer variable is called a pointer to pointer variable.
Some mes we also call it a double pointer.
Syntax:
datatype **pointerName ;
Example:
int a;
p1 = &a;
p2 = &p1;
p3 = &p2
Note:
2. To store the address of single pointer variable we use double pointer variable
3. To store the address of double pointer variable we use triple pointer variable
A void pointer is a pointer variable used to store the address of a variable of any datatype.
That means single void pointer can be used to store the address of integer variable, float variable, character
variable, double variable or any structure variable
We use the keyword "void" to create void pointer.
Syntax:
void *pointerName ;
Example:
int a;
float b;
void *p1, *p2;
p1 = &a;
p2 = &b;
55
2. Subtrac on:
When a pointer is subtracted with an integer value, the value is first mul plied by the size of the data type
and then subtracted from the pointer similar to addi on.
The subtrac on opera on on pointer variables is calculated using the following formula:
AddressAtPointer - ( NumberToBeAdd * Datatype_Size )
For Example:
Consider the same example as above where the ptr is an integer pointer that stores 1000 as an address.
If we subtract integer 5 from it using the expression, ptr = ptr – 5, then,
the final address stored in the ptr will be ptr = 1000 – sizeof(int) * 5 = 980.
56
3. Increment:
Increment: It is a condi on that also comes under addi on. When a pointer is incremented, it actually
increments by the number equal to the size of the data type for which it is a pointer.
The increment opera on on pointer variable is calculated as follows:
AddressAtPointer + Datatype_size
For Example:
If an integer pointer that stores address 1000 is incremented, then it will increment by 4(size of an int), and the new
address will point to 1004. While if a float type pointer is incremented then it will increment by 4(size of a float) and
the new address will be 1004.
4. Decrement
It is a condi on that also comes under subtrac on. When a pointer is decremented, it actually decrements by
the number equal to the size of the data type for which it is a pointer.
The decrement opera on on pointer variable is calculated as follows:
AddressAtPointer - NumberOfBytesRequiresByDatatype
For Example:
If an integer pointer that stores address 1000 is decremented, then it will decrement by 4(size of an int), and the new
address will point to 996. While if a float type pointer is decremented then it will decrement by 4(size of a float) and
the new address will be 996.
5. Comparison
We can compare the two pointers by using the comparison operators in C.
We can implement this by using all operators in C >, >=, <, <=, ==, !=.
It returns true for the valid condi on and returns false for the unsa sfied condi on.
The comparison opera on is performing between the pointers of same datatype only.
In c programming language, we can use all comparison operators (rela onal operators) with pointers.
57
Pointers and Array representa ons are very much related to each other and can be interchangeably used in
the right context.
An array name is generally treated as a pointer to the first element of the array and if we store the base
address of the array in another pointer variable, then we can easily manipulate the array using pointer
arithme c in a C Program.
Syntax
*(arr + i)
we denote array elements as arr[i], where i is the index value. Below is a similar syntax in terms of pointers of how we
can represent the array elements using the dereferencing operator (*) on the array name i.e. using the pointers
property of the array.
* is a dereferencing operator used to extract the value from the address (arr + i).
*(arr + i) is the same as arr[i] in a C Program.
arr represents the array name and i represents the index value.
Example
#include <stdio.h>
int main()
{
// array declaration and initialization
int arr[5] = {2, 4, 6, 8, 10}, i;
for(i = 0; i < 5; i++)
{
// printing the elements address and value at
// arr[i] using *(arr + i) syntax
printf("[index %d] Address : %u, Value : %d\n", i, (arr + i), *(arr + i));
}
return 0;
}
Output :
[index 0] Address : 2364420656, Value : 2
[index 1] Address : 2364420660, Value : 4
[index 2] Address : 2364420664, Value : 6
[index 3] Address : 2364420668, Value : 8
[index 4] Address : 2364420672, Value : 10
Explana on :
We have declared and ini alized an integer array arr, array representa on :
58
(arr + i) represents the address of the value at index i, so *(arr + i) will give the value at ith index (address(arr + i)
= address(arr[i])), it is used to print the addresses of the array elements as the value of i changes from 0-4
* is a dereferencing operator used for prin ng the value at the provided address. *(arr + i) will print the values of
the array at consecu ve addresses as the value of i changes from 0-4.
Q 8. Define sta c memory alloca on. What are its limita ons.
Limita ons:
When we create an array, we must specify the size at the me of the declara on itself and it cannot be
changed during the program execu on.
This is a major problem when we do not know the number of values to be stored in an array.
Alloca on of memory during the program execu on is called dynamic memory alloca on.
We use pre-defined func ons to allocate memory dynamically.
There are FOUR pre-defined func ons that are defined in the header file known as "stdlib.h".
1. malloc()
2. calloc()
3. realloc()
4. free()
1. malloc():
malloc() is the pre-defined func on used to allocate a memory block of specified number of bytes and
returns void pointer.
The void pointer can be casted to any datatype. If malloc() func on unable to allocate memory due to any
reason it returns NULL pointer.
Syntax:
void* malloc(size_in_bytes)
Example:
char * tle;
tle = (char *) malloc(15);
59
2. calloc():
calloc() is the pre-defined func on used to allocate mul ple memory blocks of the specified number of bytes
and ini alizes them to ZERO.
calloc() func on returns void pointer.
If calloc() func on unable to allocate memory due to any reason it returns a NULL pointer.
Generally, calloc() is used to allocate memory for array and structure.
o calloc() func on takes two arguments and they are
o The number of blocks to be allocated
Size of each block in bytes
Syntax:
void* calloc(number_of_blocks, size_of_each_block_in_bytes)
Example:
int *ptr;
ptr = (int*)calloc(5, sizeof(int));
3. realloc():
realloc() is the pre-defined func on used to modify the size of memory blocks that were previously allocated
using malloc() or calloc().
realloc() func on returns void pointer.
If realloc() func on unable to allocate memory due to any reason it returns NULL pointer.
Syntax
void* realloc(*pointer, new_size_of_each_block_in_bytes)
Example:
char * tle;
tle = (char *) malloc(15);
tle = (char*) realloc( tle, 30);
4. free():
free() is the pre-defined func on used to deallocate memory block that was previously allocated using
malloc() or calloc().
Syntax
void free(*pointer)
Example:
char * tle;
tle = (char *) malloc(15);
free( tle);
60
{
//store first employee information
e1.id=101;
e1.name = "Ajay");
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
return 0;
}
Output:
employee 1 id : 101
employee 1 name : Ajay
#include<stdio.h>
struct student
{
int rollno;
62
char name[10];
};
int main()
{
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++)
{
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++)
{
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}
Output:
Enter Records of 5 students
Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz
Student Information List:
Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz
63
Q 14. Define union. Explain crea on of union and accessing union members.
Union:
Union is a collec on of different datatype elements which can be referred under a single name.
Crea ng Union:
To create union, we use the keyword called “union”.
Syntax:
union union_name
{
// Union members
data_type member1;
data_type member2, member3;
….
};
union union_name union_varaibles;
Example:
union Student
{
// union members
64
char stud_name[30];
int roll_number;
float percentage;
};
// union variables
union Student s1,s2;
Accessing Union Members:
We use union variables to access structure members with dot(.) operator.
Syntax:
Union_varaible . Union_member
Example:
s1.stud_name
s1.roll_number
s1.percentage
Q 15 How much memory is allocated for a Union?
The memory is allocated when we create the variable of a par cular union.
The size of memory allocated is equal to the maximum memory required by an individual member among all
members of that union.