Unit-IV
Unit-IV
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 manipulation.
Declaring Pointer:
Declaration of pointer variable is similar to the creation of normal variable but the name is prefixed with *
symbol.
Syntax:
datatype *pointerName ;
Example:
int *ptr ;
In the above example declaration, the variable "ptr" is a pointer variable that can be used to store any integer
variable address.
Initializing a Pointer:
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 pointing.
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 printf statement to display memory location address of variable "marks".
➢ Example:
printf("Address : %u", &marks) ;
➢ In the above example statement %u is used to display address of marks variable.
➢ Address of any memory location is unsigned integer value.
➢ A pointer variable to store the address of another pointer variable is called a pointer to pointer variable.
➢ Sometimes 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. Subtraction:
➢ When a pointer is subtracted with an integer value, the value is first multiplied by the size of the data type
and then subtracted from the pointer similar to addition.
➢ The subtraction operation 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 condition that also comes under addition. 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 operation 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 condition that also comes under subtraction. 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 operation 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 condition and returns false for the unsatisfied condition.
➢ The comparison operation is performing between the pointers of same datatype only.
➢ In c programming language, we can use all comparison operators (relational operators) with pointers.
57
✓ Pointers and Array representations 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
arithmetic 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
Explanation :
✓ (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 printing the value at the provided address. *(arr + i) will print the values of
the array at consecutive addresses as the value of i changes from 0-4.
Q 8. Define static memory allocation. What are its limitations.
Limitations:
➢ When we create an array, we must specify the size at the time of the declaration itself and it cannot be
changed during the program execution.
➢ This is a major problem when we do not know the number of values to be stored in an array.
➢ Allocation of memory during the program execution is called dynamic memory allocation.
➢ We use pre-defined functions to allocate memory dynamically.
➢ There are FOUR pre-defined functions 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 function 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() function unable to allocate memory due to any
reason it returns NULL pointer.
Syntax:
void* malloc(size_in_bytes)
Example:
char *title;
title = (char *) malloc(15);
59
2. calloc():
➢ calloc() is the pre-defined function used to allocate multiple memory blocks of the specified number of bytes
and initializes them to ZERO.
➢ calloc() function returns void pointer.
➢ If calloc() function 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() function 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 function used to modify the size of memory blocks that were previously allocated
using malloc() or calloc().
➢ realloc() function returns void pointer.
➢ If realloc() function 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 *title;
title = (char *) malloc(15);
title = (char*) realloc(title, 30);
4. free():
➢ free() is the pre-defined function used to deallocate memory block that was previously allocated using
malloc() or calloc().
Syntax
void free(*pointer)
Example:
char *title;
title = (char *) malloc(15);
free(title);
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 creation of union and accessing union members.
Union:
Union is a collection of different datatype elements which can be referred under a single name.
Creating 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 particular union.
➢ The size of memory allocated is equal to the maximum memory required by an individual member among all
members of that union.