MCS-011 Problem Solving and Programming

First year, Semester 1

Chapters

Newsletter

Passing Pointers to Functions

Passing pointers to functions is a powerful technique in C programming that allows functions to modify variables outside their local scope, work with arrays efficiently, and manage dynamic memory. Here’s a detailed explanation with examples:

Why Pass Pointers to Functions?

  1. Modify Original Variables: Functions can modify the actual variables passed to them, not just copies.
  2. Efficiently Handle Arrays: Arrays are always passed by reference using pointers, avoiding the overhead of copying large amounts of data.
  3. Dynamic Memory Management: Functions can dynamically allocate, modify, and deallocate memory.


How to Pass Pointers to Functions

When passing a pointer to a function, you provide the address of the variable. The function can then use the pointer to access and modify the original variable.

Syntax

void functionName(type *pointerName) { // Function body }

here, type *pointerName: A pointer parameter that will receive the address of a variable.


Example : Modifying an Integer Variable

#include
// Function to modify the value of an integer void modifyValue(int *ptr) { *ptr = 20; // Dereference the pointer and change the value at that address } int main() { int x = 10; printf("Before: x = %d\n", x); modifyValue(&x); // Pass the address of x to the function printf("After: x = %d\n", x); return 0; }


In C programming, functions can receive arguments using two primary methods: pass by value and pass by reference. Understanding these methods is crucial for managing how data is passed to functions and how changes to that data are handled.

Pass by Value

Pass by value means that when a function is called, the values of the arguments are copied to the function's parameters. Any changes made to the parameters within the function do not affect the original arguments.

Example

#include <stdio.h>
// Function to swap two integers (incorrectly using pass by value) void swap(int a, int b) { int temp = a; a = b; b = temp; } int main() { int x = 10; int y = 20; printf("Before swap: x = %d, y = %d\n", x, y); swap(x, y); // Pass by value printf("After swap: x = %d, y = %d\n", x, y); return 0; }


Pass by Reference

Pass by reference means that when a function is called, the addresses of the arguments are passed to the function's parameters. Any changes made to the parameters within the function do affect the original arguments.

Example

#include <stdio.h>
// Function to swap two integers (correctly using pass by reference) void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } int main() { int x = 10; int y = 20; printf("Before swap: x = %d, y = %d\n", x, y); swap(&x, &y); // Pass by reference printf("After swap: x = %d, y = %d\n", x, y); return 0; }


Report an issue

Reporting: Passing Pointers to Functions (topic)

Related Posts