Unit 4 Part B Study Material
Unit 4 Part B Study Material
Here's why:
• Pointer becomes a dangling pointer: The pointer that was previously pointing
to the freed memory now becomes a dangling pointer.
• Access to invalid memory: Accessing the memory through the dangling pointer
can lead to unpredictable results.
PS & PwC Unit 4
Address Arithmetic in C
Address arithmetic in C refers to the operations that can be performed on pointer
variables to navigate through arrays or memory locations. Since pointers store memory
addresses, arithmetic operations allow you to calculate and manipulate these addresses
effectively. The arithmetic operations on pointers take into account the size of the data
type to which the pointer points.
Arithmetic Operations on Pointers
1. Pointer Increment (++):
• When you increment a pointer (e.g., ptr++), it moves to the next memory
location based on the size of the data type it points to. For example, if ptr is
an int*, incrementing it will move the pointer forward by sizeof(int) bytes
int arr[] = {10, 20, 30};
int* ptr = arr; // Points to arr[0]
ptr++; // Now points to arr[1]
2. Pointer Decrement (--):
• Similar to incrementing, decrementing a pointer (e.g., ptr--) moves it to the
previous memory location based on the size of the data type.
int* ptr = arr + 2; // Points to arr[2]
ptr--; // Now points to arr[1]
3. Pointer Addition:
• You can add an integer value to a pointer (e.g., ptr + n), which moves the
pointer forward by n elements of the type it points to.
int* ptr = arr; // Points to arr[0]
ptr = ptr + 2; // Now points to arr[2]
4. Pointer Subtraction:
• You can subtract an integer from a pointer (e.g., ptr - n), which moves the
pointer backward by n elements.
int* ptr = arr + 2; // Points to arr[2]
ptr = ptr - 1; // Now points to arr[1]
5. Pointer Difference:
• You can subtract one pointer from another if both pointers point to
elements of the same array. This operation returns the number of elements
between the two pointers.
int* ptr1 = arr; // Points to arr[0]
int* ptr2 = arr + 2; // Points to arr[2]
int diff = ptr2 - ptr1; // diff will be 2
6. Pointer Comparison
• In C, pointers can be compared using relational operators. This comparison
is useful for various purposes, such as checking if two pointers refer to the
same memory location or determining their relative positions in memory
(e.g., whether one pointer points to an address before or after another).
Example Program:
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr; // ptr points to the first element of the array
// Accessing elements using pointer arithmetic
printf("%d\n", *(ptr + 1)); // Prints 20
printf("%d\n", *(ptr + 2)); // Prints 30
// Comparing pointers
if (ptr < (ptr + 3)) {
printf("ptr is less than ptr + 3\n");}
PS & PwC Unit 4
4. Expected Output:
Enter two integers: 10 5
Sum: 15
Difference: 5
Product: 50
Quotient: 2
4. Develop a program using pointers to compute the sum of all elements stored in an
array.
1. Analysis
Problem Description:
We are tasked with computing the sum of all elements stored in an array. Instead of
using array indices, we will use pointers to access and manipulate the elements of the
array. This method allows us to work directly with memory addresses, showcasing the
flexibility of pointers in C.
Technique Chosen:
We will use pointer arithmetic to traverse through the array. A pointer will be
initialized to point to the first element of the array, and we will move the pointer
through the array to access each element and calculate the sum.
Approach:
• The pointer will point to the first element of the array.
• We will iterate through the array using the pointer, dereferencing it to access
each element.
• The sum will be updated as we go through the array.
2. Algorithm
Algorithm for main Function
1. Start.
2. Declare an integer array arr[] and an integer variable sum.
3. Input the size of the array (number of elements).
4. Input the elements of the array.
5. Call the sumArray function, passing the array and its size.
6. Display the sum.
7. Stop.
Algorithm for sumArray Function
1. Start.
2. Declare an integer pointer ptr and initialize it to point to the first element of the
array.
3. Initialize a variable sum = 0.
4. Iterate through the array:
o For each element, dereference the pointer and add the value to sum.
o Increment the pointer to move to the next element.
5. Return the sum.
6. End
3. Program
#include <stdio.h>
// Function to compute the sum of all elements in the array using pointers
int sumArray(int *arr, int size) {
int sum = 0;
int *ptr = arr; // Pointer to the first element of the array
// Iterate through the array using pointer arithmetic
for (int i = 0; i < size; i++) {
sum += *ptr; // Add the value at the current pointer location
PS & PwC Unit 4
The functions malloc () and calloc () are library functions that allocate memory
dynamically. Dynamic means the memory is allocated during runtime (execution of
the program) from the heap segment.
Initialization
malloc() (Memory Alloc) allocates a memory block of given size (in bytes) and returns
a pointer to the beginning of the block. malloc() doesn’t initialize the allocated
memory. If you try to read from the allocated memory without first initializing it,
then you will invoke undefined behaviour, which usually means the values you read
will be garbage values.
PS & PwC Unit 4
calloc() (Contiguous Alloc) allocates the memory and also initializes every byte in the
allocated memory to 0. If you try to read the value of the allocated memory without
initializing it, you’ll get 0 as it has already been initialized to 0 by calloc().
Parameters
malloc() takes a single argument, which is the number of bytes to allocate.
Unlike malloc(), calloc() takes two arguments:
1. Number of blocks to be allocated.
2. Size of each block in bytes.
Return Value
After successful allocation in malloc() and calloc(), a pointer to the block of memory is
returned otherwise NULL is returned which indicates failure.
S.No Feature malloc calloc
Allocates a single block of Allocates contiguous blocks of
1 Purpose
memory memory
2 Parameters size_t size size_t num, size_t size
Multiple blocks, each of specified
3 Memory Allocation One block of specified size
size
4 Speed Faster Slower
5 Time Efficiency High Low
6 Initialization Does not initialize memory Initializes memory to zero
May add some overhead for
7 Memory Overhead No
bookkeeping
8 Syntax void* malloc(size_t size); void* calloc(size_t num, size_t size);
3. realloc() - Reallocation
The realloc() function is used to change the size of previously allocated memory. It can
either expand or reduce the size of the memory block. The syntax is:
void* realloc(void* ptr, size_t new_size);
• ptr: The pointer to the previously allocated memory.
• new_size: The new size of the memory block in bytes.
• Returns a pointer to the reallocated memory, or NULL if the reallocation fails.
Example:
ptr = (int*)realloc(ptr, 10 * sizeof(int));
This reallocates the memory to hold 10 integers.
4. free() - Deallocation
The free() function is used to release the memory that was dynamically allocated using
malloc(), calloc(), or realloc(). The syntax is:
void free(void* ptr);
• ptr: The pointer to the memory block to be freed.
Example:
free(ptr);
This frees the memory previously allocated to ptr.
#include <stdio.h>
#include <stdlib.h>
int main() {
int* ptr;
int n;
// Dynamically allocate memory for 5 integers using malloc
printf("Enter the number of elements: ");
scanf("%d", &n);
ptr = (int*)malloc(n * sizeof(int)); // malloc: allocate memory
// Check if malloc failed
if (ptr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
Expected Output:
Enter the number of elements: 5
Enter 5 elements:
12345
Entered elements are:
12345
Reallocating memory to hold 10 elements.
Enter 5 more elements:
6 7 8 9 10
All elements are:
1 2 3 4 5 6 7 8 9 10