0% found this document useful (0 votes)
3 views11 pages

CTSD Pract3 - Merged

The document provides practical exercises on using pointers in C programming, including accessing variables, swapping numbers, and accessing array elements through pointers. It also covers advanced topics such as arrays of pointers to strings, pointers to pointers, and the differences between call by value and call by reference. Each section includes code examples demonstrating the concepts discussed.

Uploaded by

somashekartm08
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views11 pages

CTSD Pract3 - Merged

The document provides practical exercises on using pointers in C programming, including accessing variables, swapping numbers, and accessing array elements through pointers. It also covers advanced topics such as arrays of pointers to strings, pointers to pointers, and the differences between call by value and call by reference. Each section includes code examples demonstrating the concepts discussed.

Uploaded by

somashekartm08
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Practical No.

: 03

Title:
1. Write a program to demonstrate how to access a variable using its pointer.
2. Write a program to swap two numbers using pointers.
3. Write a program to demonstrate accessing array element using pointers.

Accessing a Variable Using Its Pointer in C

Introduction to Pointers
A pointer is a variable that stores the memory address of another variable. Pointers are widely
used in C programming to efficiently manipulate data, allocate memory dynamically, and
optimize performance.

Concept of Pointers

A pointer variable is declared using the * (asterisk) symbol. It holds the address of another
variable, allowing indirect access to that variable’s value. The & (address-of) operator is used
to retrieve the memory address of a variable.

Syntax of Pointers
data_type *pointer_name;

Here, data_type represents the type of data the pointer will point to, and pointer_name is the
name of the pointer variable.

Accessing a Variable Using a Pointer


1. Declare a variable.
2. Declare a pointer and store the address of the variable using the & operator.

3. Access the value of the variable using the pointer and the * (dereference) operator.

Swapping of Two Numbers Using Pointers in C

Introduction
Swapping two numbers means exchanging their values. This can be done using different
methods such as using a temporary variable, arithmetic operations, or bitwise XOR. In this
case, we will swap two numbers using pointers, which allows direct manipulation of memory
addresses.

Enrollment No: - 2403031050464


Concept of Pointers in Swapping
Pointers store the memory addresses of variables. By passing the addresses of two variables
to a function, we can swap their values directly in memory without returning any value from
the function. This is particularly useful in function-based swapping since changes persist
outside the function.

Working of Swapping Using Pointers


1. Declare two integer variables to store numbers.
2. Declare two pointer variables to store the addresses of these numbers.
3. Use a temporary variable to swap the values indirectly through pointers.
4. The function modifies the values at the given memory addresses.

Advantages of Using Pointers for Swapping


1. Efficient Memory Usage – No need to return values, as changes occur at memory
locations.
2. No Extra Variables in Main Function – The swapping logic is handled in a separate
function.
3. Used in Advanced Applications – Useful in sorting algorithms, linked lists, and
dynamic memory allocation.

Accessing Array Elements Using Pointers in C

Introduction to Pointers and Arrays


In C, an array is a collection of elements stored in contiguous memory locations. Pointers
provide an efficient way to access and manipulate array elements by pointing to their memory
addresses. Instead of using array indexing (arr[i]), we can use pointer arithmetic to traverse
an array.

Pointer and Array Relationship

The name of an array acts as a pointer to its first element. That means, if arr is an array, then:

● arr is equivalent to &arr[0] (address of the first element).


● *(arr + i) is equivalent to arr[i] (value at index i).

Using pointers, we can iterate through the array without using the traditional subscript
notation ([]).

Accessing Array Elements Using Pointers


1. Declare and initialize an array.
2. Declare a pointer and assign the array's base address to it.

Enrollment No: - 2403031050464


3. Use pointer arithmetic (ptr + i) to access and print each element.

Advantages of Using Pointers for Array Access


1. Efficiency – Accessing array elements through pointers is faster than using indices in
some cases.
2. Memory Optimization – Avoids extra variables and can be useful in low-memory
systems.
3. Useful in Dynamic Memory Allocation – Helps in handling arrays created using
malloc() or calloc().

Conclusion :

Enrollment No: - 2403031050464


3.1
#include <stdio.h>

int main()
{
int num = 10; // Declare an integer variable
int *ptr = &num; // Declare a pointer and store the address of num

printf("Value of num: %d\n", num);


printf("Address of num: %p\n", &num);

// Display the value of num using the pointer


printf("Value stored at pointer ptr: %d\n", *ptr);
printf("Address stored in pointer ptr: %p\n", ptr);

return 0;
}

Output:-

3.2
#include <stdio.h>

// Function to swap two numbers using pointers


void swap(int *a, int *b)
{
int temp; // Declare a temporary variable
temp = *a; // Store the value of *a in temp
*a = *b; // Assign the value of *b to *a
*b = temp; // Assign the value of temp to *b
}

int main()
{
int n1, n2; // Declare two integer variables
// Ask the user to enter two numbers
printf("Enter the values of n1 and n2:\n");
scanf("%d %d", &n1, &n2); // Read input values from the user

// Display the values before swapping

Enrollment No: - 2403031050464


printf("Before swapping: n1 = %d, n2 = %d\n", n1, n2);

// Call the swap function with addresses of n1 and n2


swap(&n1, &n2);

// Display the values after swapping


printf("After swapping: n1 = %d, n2 = %d\n", n1, n2);

return 0; // End of program


}

Output:-

3.3
// Write a program to demonstrate accessing array elements using pointers
#include <stdio.h>

int main()
{
int arr[] = {1, 2, 3, 4, 5}; // Declare and initialize an array
int i, *ptr = arr; // Declare a pointer and assign it to the first element of the array
printf("Accessing array elements using pointers:\n");
// Loop through the array using a pointer
for (i = 0; i < 5; i++)
{
printf("Element %d: %d\n", i, *(ptr + i)); // Access array elements using pointer
arithmetic
}
return 0; // End of program
}

Output:-

Enrollment No: - 2403031050464


Practical : 04
Title:
1. Write a program to demonstrate an array of pointers to strings.
2. Write a program to demonstrate the use of a pointer to a pointer.
3. Write a program to demonstrate the call by value and call by reference.

Array of Pointers to Strings in C


Introduction

In C programming, an array of pointers to strings is an efficient way to store and manipulate multiple
strings. Instead of using a 2D character array, we store string literals as pointers, making memory
usage more efficient.

Concept of Array of Pointers to Strings

● Each string is stored as a character pointer (char *).


● An array of character pointers (char *arr[]) holds multiple string addresses.
● Using pointers reduces memory usage since only addresses are stored, not fixed-size character
arrays.

Advantages of Using an Array of Pointers to Strings


1. Efficient Memory Usage:
○ Unlike a 2D character array, only the addresses of strings are stored, saving memory.
2. Flexibility:
○ Strings can have different lengths without wasting space.
3. Faster String Manipulation:
○ No need to copy entire strings, just update pointers if needed.
4. Ease of Modification:
○ Pointers can be reassigned to different strings dynamically.

Pointer to a Pointer in C
Introduction
In C, a pointer to a pointer (also called a double pointer) is a pointer that stores the address of another
pointer. It allows multiple levels of indirection, meaning that instead of pointing to a variable, it points
to another pointer that in turn points to a variable.

Enrollment No: - 2403031050464


Concept of Pointer to a Pointer A

pointer to a pointer is declared as:

int **ptr2; // ptr2 is a pointer to a pointer to an int

If we have: int num = 10; int *ptr = &num; //

ptr stores the address of num int **ptr2 = &ptr;

// ptr2 stores the address of ptr Then:

● num contains 10.


● ptr stores the address of num.
● ptr2 stores the address of ptr.
This allows accessing num in three ways:
● num (direct access).
● *ptr (dereferencing single pointer).
● **ptr2 (dereferencing double pointer).
Use Cases of Pointer to a Pointer
1. Dynamic Memory Allocation – Used in malloc() for 2D arrays.
2. Function Arguments – Used to modify a pointer in a function.
3. Handling Arrays of Strings – Used in command-line arguments (char **argv).

Advantages of Pointer to a Pointer


1. Modifying a Pointer in a Function:
○ Used in functions that need to modify pointer arguments.
2. Efficiently Managing Memory in 2D Arrays:
○ Used in dynamic memory allocation (malloc for 2D arrays).
3. Useful in Data Structures:
○ Used in linked lists, trees, and graphs for efficient memory handling.

Call by Value and Call by Reference in C


Introduction

In C, functions can pass arguments in two ways:

1. Call by Value – A copy of the variable is passed to the function. Any changes inside the
function do not affect the original value.
2. Call by Reference – A memory address (pointer) of the variable is passed to the function. Any
changes inside the function affect the original value.

Call by Value
● In Call by Value, the function creates a local copy of the passed variable.

Enrollment No: - 2403031050464


● Changes made inside the function do not affect the original variable.

Call by Reference
● In Call by Reference, a pointer to the original variable is passed to the function.
● The function modifies the actual value stored at the memory address.

Comparison of Call by Value vs. Call by Reference


Feature Call by Value Call by Reference

Passing Passes a copy of the value Passes the address (pointer)


Mechanism
Modification Changes remain inside the function Changes affect the original
Effect variable
Memory Usage Uses more memory (creates a copy) Uses less memory (modifies
directly)

Use Cases When we don't want the function to When we need to modify the
modify the original value original variable

Conclusion:-

Enrollment No: - 2403031050464


4.1
#include <stdio.h> // Include standard input-output library for printf function

int main()
{
// Declare an array of string pointers (array of character pointers)
// Each element is a pointer to a string literal
const char *strings[] = {"Hello", "Welcome", "to", "Parul", "University"};

// Get the number of elements in the array (size of array / size of one element)
int i, size = sizeof(strings) / sizeof(strings[0]);

// Print a message indicating that strings will be accessed using an array of pointers
printf("Accessing strings using an array of pointers:\n");

// Loop through the array to print each string


for (i = 0; i < size; i++)
{
printf("String %d: %s\n", i, strings[i]); // Print index and corresponding string
}

return 0; // Return 0 to indicate successful execution


}

Output :-

4.2
#include <stdio.h> // Include standard input-output library for printf function

int main()
{
int num = 10; // Declare an integer variable and initialize it with 10

int *ptr = &num; // Declare a pointer `ptr` and store the address of `num`
int **ptr2 = &ptr; // Declare a pointer to a pointer `ptr2` and store the address of `ptr`

// Print the value of `num` directly


printf("Value of num: %d\n", num);

// Print the value of `num` using a single pointer (dereferencing `ptr`)


printf("Value using single pointer: %d\n", *ptr);

Enrollment No: - 2403031050464


// Print the value of `num` using a double pointer (dereferencing `ptr2` twice)
printf("Value using double pointer: %d\n", **ptr2);

// Print the address of `num` using `&num`


printf("Address of num: %p\n", (void*)&num);

// Print the address stored in `ptr` (which is the address of `num`)


printf("Address stored in ptr: %p\n", (void*)ptr);

// Print the address stored in `ptr2` (which is the address of `ptr`)


printf("Address stored in ptr2 (address of ptr): %p\n", (void*)ptr2);

return 0; // Return 0 to indicate successful execution


}

Output :-

4.3
#include <stdio.h> // Include standard input-output library for printf function

// Function demonstrating Call by Value


void callByValue(int num)
{
// The parameter `num` receives a copy of the actual argument
num = 20; // Modify `num` (this change will not reflect in the original variable)
printf("Inside callByValue function: num = %d\n", num);
}

// Function demonstrating Call by Reference


void callByReference(int *num)
{
// The parameter `num` is a pointer to an integer
*num = 20; // Modify the value at the memory address stored in `num`
printf("Inside callByReference function: num = %d\n", *num);
}

int main()
{

Enrollment No: - 2403031050464


int num1 = 10, num2 = 10; // Declare two integer variables with initial value 10

// Demonstrate Call by Value


printf("Before callByValue: num1 = %d\n", num1); // Print initial value of num1
callByValue(num1); // Call function with value (copy of num1 is passed)
printf("After callByValue: num1 = %d\n", num1); // Original num1 remains unchanged

// Demonstrate Call by Reference


printf("Before callByReference: num2 = %d\n", num2); // Print initial value of num2
callByReference(&num2); // Call function with address of num2 (pass by reference)
printf("After callByReference: num2 = %d\n", num2); // Original num2 is modified

return 0; // Return 0 to indicate successful execution


}

Output :-

Enrollment No: - 2403031050464

You might also like