Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> C Language

C Programming: Passing Addresses & Pointers to Functions – A Practical Guide

C Programming: Passing Addresses & Pointers to Functions

Master how to pass memory addresses and pointers to functions in C, with clear examples and expert explanations.

In C, passing an address instead of a value lets a function directly manipulate the original variable. This technique, called pointer passing, is essential for efficient code and for modifying data across scopes.

Example 1: Swapping Two Integers by Reference

#include <stdio.h>

void swap(int *n1, int *n2);

int main(void)
{
    int num1 = 5, num2 = 10;

    /* Pass the addresses of num1 and num2 */
    swap(&num1, &num2);

    printf("num1 = %d\n", num1);
    printf("num2 = %d", num2);
    return 0;
}

void swap(int *n1, int *n2)
{
    int temp = *n1;
    *n1 = *n2;
    *n2 = temp;
}

Running this program produces:

num1 = 10
num2 = 5

The swap() function receives pointers n1 and n2 that point to the original num1 and num2 variables. By dereferencing these pointers (*n1 and *n2), the function swaps the actual values stored in memory, which is why main() sees the updated numbers. Notice that swap() returns void because it modifies its arguments directly.

Example 2: Incrementing a Value via a Pointer

#include <stdio.h>

void addOne(int *ptr)
{
    (*ptr)++;   /* Increment the value at the given address */
}

int main(void)
{
    int i = 10;
    int *p = &i;

    addOne(p);

    printf("%d", *p); /* Prints 11 */
    return 0;
}

Here, p holds the address of i. The addOne() function receives that same address, dereferences it, and increments the underlying value. After the call, *p (and consequently i) reflects the new value of 11.

These examples illustrate the power of pointer passing: functions can alter variables defined outside their scope, enabling efficient data manipulation without unnecessary copying.

C Language

  1. Mastering C# While and Do‑While Loops: Syntax, Examples, and Best Practices
  2. How to Pass and Return Objects in C++ Functions
  3. C++ Pointers and Arrays: Mastering the Relationship
  4. Mastering While and Do‑While Loops in C: Practical Examples
  5. Mastering C Pointers: A Practical, Expert‑Guided Tutorial
  6. Understanding the Relationship Between Arrays and Pointers in C
  7. Mastering C Structs and Pointers: A Practical Guide
  8. Understanding C Constants and Literals: Types, Usage, and Best Practices
  9. Mastering C Pointers: Practical Steps to Advanced Programming
  10. Mastering C# Constants & Literals: Types, Rules, and Best Practices