0% found this document useful (0 votes)
12 views8 pages

Index 9

Uploaded by

sahanush6
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)
12 views8 pages

Index 9

Uploaded by

sahanush6
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/ 8

Index 9 SET: A

Title of the Program: C | Pointer (Part 1 & Part 2)

Objectives

• To understand the concept of pointers, their declaration, initialization, and dereferencing.


• To apply pointer arithmetic and use pointers to access array elements.
• To implement pass-by-reference using pointers in functions.

Requirements

1. Computer System
2. C Compiler
3. Integrated Development Environment (IDE) / Text Editor

Theory: Understanding Pointers

In C programming, a pointer is a variable that stores the memory address of another variable.
Instead of storing a direct value, it stores the location (address) where a value is stored in memory.
Pointers are powerful features that allow direct memory access.

Pointer Declaration and Initialization

A pointer variable must be declared to point to a specific data type. The * (asterisk) symbol is
used to declare a pointer.

Syntax:

data_type *pointer_name;

Example:

int *ptr; // Declares a pointer 'ptr' that can hold the address of an integer
variable.
char *chPtr; // Declares a pointer 'chPtr' that can hold the address of a
character variable.

To initialize a pointer, you assign it the address of an existing variable using the & (address-of)
operator.

Computer Department-KMC, Bagbazar


Example:

int num = 10;


int *ptr = # // 'ptr' now holds the memory address of 'num'.

It's good practice to initialize pointers to NULL if they are not pointing to any valid memory location
immediately, to avoid dangling pointer issues.

int *ptr = NULL;

Dereferencing Pointers

Dereferencing (or indirection) is the process of accessing the value stored at the memory address
pointed to by a pointer. This is also done using the * (asterisk) operator.

Syntax:

*pointer_name; // Gives the value at the address stored in pointer_name.

Example:

int num = 10;


int *ptr = #
printf("Value of num: %d\n", num); // Output: 10
printf("Value via pointer: %d\n", *ptr); // Output: 10 (accesses value at
address stored in ptr)

Pointer Arithmetic

Pointers can be incremented or decremented, but this arithmetic is scaled by the size of the data
type the pointer points to.

• pointer_name + n: Moves the pointer n times the size of its data type forward in
memory.
• pointer_name - n: Moves the pointer n times the size of its data type backward in
memory.
• pointer_name++: Increments the pointer to point to the next memory location of its data
type.
• pointer_name--: Decrements the pointer to point to the previous memory location of its
data type.

Computer Department-KMC, Bagbazar


Pointers and Arrays

Arrays and pointers are closely related in C. The name of an array itself acts as a constant pointer
to its first element.

Example:

int arr[5] = {10, 20, 30, 40, 50};


int *ptr = arr; // 'ptr' now points to arr[0]
printf("%d\n", *ptr); // Output: 10
printf("%d\n", *(ptr + 1)); // Output: 20 (equivalent to arr[1])
printf("%d\n", arr[2]); // Output: 30
printf("%d\n", *(arr + 2)); // Output: 30 (equivalent to arr[2])

Pointers and Functions (Pass by Reference)

Pointers are essential for "pass by reference" in C. When you pass a variable's address to a function,
the function can modify the original variable's value.

Example (Swap function):

void swap(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}

int main() {
int x = 5, y = 10;
swap(&x, &y); // Pass addresses
// x is now 10, y is now 5
return 0;
}

Pointers to Pointers (Double Pointers)

A pointer to a pointer (or double pointer) is a variable that stores the address of another pointer.
This is useful in scenarios where you need to modify a pointer itself within a function or when
dealing with multi-dimensional arrays.

Syntax:

data_type **ptr_to_ptr;

Example:

Computer Department-KMC, Bagbazar


int num = 10;
int *ptr = #
int **pptr = &ptr; // pptr stores the address of ptr
printf("Value: %d\n", **pptr); // Accesses num's value

Part 1: Basic Pointer Concepts

Problem 1: Pointer Declaration, Initialization, and Dereferencing

Write a C program to declare an integer variable, initialize it, declare a pointer to this integer, and
then print the value of the integer, its memory address, the value stored in the pointer, and the
value accessed through the pointer (dereferencing).

C Program:

#include <stdio.h>

int main() {
int num = 25; // Declare and initialize an integer variable
int *ptr; // Declare a pointer to an integer

ptr = &num; // Initialize the pointer with the address of 'num'

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


printf("Address of num: %p\n",&num); // Use %p for addresses,
printf("Value stored in ptr (address of num): %p\n",ptr);
printf("Value accessed through ptr (*ptr): %d\n", *ptr);

return 0;
}

Output (example):

Value of num: 25
Address of num: 0x7ffee5f0a00c
Value stored in ptr (address of num): 0x7ffee5f0a00c
Value accessed through ptr (*ptr): 25

Problem 2: Comprehensive Pointer Arithmetic

Computer Department-KMC, Bagbazar


Write a C program to declare an integer array and a pointer initialized to the first element.
Demonstrate pointer arithmetic using +, -, ++, and -- operators to access different elements of the
array. Print the values and addresses at each step.

C Program:

#include <stdio.h>

int main() {
int arr[] = {10, 20, 30, 40, 50}; // Declare and initialize an integer
array
int *ptr = arr; // Initialize pointer to the first
element (arr[0])

printf("Original pointer (points to arr[0]):\n");


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

// Using ptr + n
printf("\nUsing ptr + 2 (points to arr[2]):\n");
printf("Value: %d, Address: %p\n", *(ptr + 2),(ptr + 2));

// Using ptr - n (after incrementing ptr for demonstration)


ptr = ptr + 4; // Move ptr to arr[4]
printf("\nPointer moved to arr[4]:\n");
printf("Value: %d, Address: %p\n", *ptr,ptr);

printf("\nUsing ptr - 2 (from arr[4], points to arr[2]):\n");


printf("Value: %d, Address: %p\n", *(ptr - 2),(ptr - 2));

// Using ptr++
ptr = arr; // Reset ptr to arr[0]
printf("\nReset ptr to arr[0]. Using ptr++:\n");
printf("Initial value: %d, Address: %p\n", *ptr,ptr);
ptr++; // Increment ptr
printf("After ptr++ (points to arr[1]): Value: %d, Address: %p\n",
*ptr,ptr);

// Using ptr--
ptr++; // Move ptr to arr[2] for demonstration
printf("\nPointer moved to arr[2]. Using ptr--:\n");
printf("Initial value: %d, Address: %p\n", *ptr,ptr);
ptr--; // Decrement ptr
printf("After ptr-- (points to arr[1]): Value: %d, Address: %p\n", *ptr,
ptr);

return 0;
}

Output (example):

Original pointer (points to arr[0]):


Value: 10, Address: 0x7ffee5f0a020

Computer Department-KMC, Bagbazar


Using ptr + 2 (points to arr[2]):
Value: 30, Address: 0x7ffee5f0a028

Pointer moved to arr[4]:


Value: 50, Address: 0x7ffee5f0a030

Using ptr - 2 (from arr[4], points to arr[2]):


Value: 30, Address: 0x7ffee5f0a028

Reset ptr to arr[0]. Using ptr++:


Initial value: 10, Address: 0x7ffee5f0a020
After ptr++ (points to arr[1]): Value: 20, Address: 0x7ffee5f0a024

Pointer moved to arr[2]. Using ptr--:


Initial value: 30, Address: 0x7ffee5f0a028
After ptr-- (points to arr[1]): Value: 20, Address: 0x7ffee5f0a024

(Note: Addresses will vary based on your system and compiler.)

Problem 3: Pass by Reference using Pointers

Write a C program that includes a function swap that takes two integer pointers as arguments and
swaps the values of the variables they point to. Demonstrate its usage in main().

C Program:

#include <stdio.h>

// UDF Prototype: Function to swap two integers using pointers (pass by


reference)
void swap(int *a, int *b);

int main() {
int x = 100, y = 200;

printf("Before swap: x = %d, y = %d\n", x, y);

// Call the swap function, passing the addresses of x and y


swap(&x, &y);

printf("After swap: x = %d, y = %d\n", x, y);

return 0;
}

// UDF Definition: Function to swap two integers using pointers (pass by


reference)
void swap(int *a, int *b) {
int temp;
temp = *a; // Store the value pointed to by 'a'
*a = *b; // Assign the value pointed to by 'b' to the location pointed
to by 'a'
*b = temp; // Assign the stored value to the location pointed to by 'b'

Computer Department-KMC, Bagbazar


}

Output (example):

Before swap: x = 100, y = 200


After swap: x = 200, y = 100

Part 2: Double Pointer Concepts

Problem 4: Pointers to Pointers (Double Pointers)

Write a C program to demonstrate the use of a pointer to a pointer. Declare an integer variable, a
pointer to that integer, and then a pointer to the first pointer. Print the value of the integer using
the double pointer.

C Program:

#include <stdio.h>

int main() {
int value = 50; // An integer variable
int *ptr1 = &value; // A pointer to 'value'
int **ptr2 = &ptr1; // A pointer to 'ptr1' (a double pointer)

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


printf("Value using ptr1 (*ptr1): %d\n", *ptr1);
printf("Value using ptr2 (**ptr2): %d\n", **ptr2);

printf("\nAddress of 'value': %p\n", &value);


printf("Address stored in ptr1: %p\n", ptr1);
printf("Address of ptr1: %p\n", &ptr1);
printf("Address stored in ptr2: %p\n",ptr2);

return 0;
}

Output (example):

Value of 'value': 50
Value using ptr1 (*ptr1): 50
Value using ptr2 (**ptr2): 50

Address of 'value': 0x7ffee5f0a00c


Address stored in ptr1: 0x7ffee5f0a00c
Address of ptr1: 0x7ffee5f0a008
Address stored in ptr2: 0x7ffee5f0a008

(Note: Addresses will vary based on your system and compiler.)

Computer Department-KMC, Bagbazar


Conclusion
By completing these exercises, students have gained a thorough understanding of pointers in C,
from their basic declaration and use to more advanced concepts like pointer arithmetic and pass-
by-reference mechanisms. The practical implementation of these concepts has provided hands-on
experience in managing memory access, which is a critical skill for developing robust and efficient
C applications.

Computer Department-KMC, Bagbazar

You might also like