0
0
CHow-ToBeginner · 3 min read

How to Pass Pointer to Function in C: Simple Guide

In C, you pass a pointer to a function by declaring the function parameter as a pointer type using *. Then, you call the function passing the address of a variable using the & operator or a pointer variable directly.
📐

Syntax

To pass a pointer to a function, declare the function parameter with an asterisk * to indicate it is a pointer. When calling the function, pass the address of a variable using & or a pointer variable.

  • Function declaration: void func(int *ptr) means func expects a pointer to an int.
  • Function call: func(&var) passes the address of var.
c
void func(int *ptr) {
    // use *ptr to access the value
}

int main() {
    int var = 10;
    func(&var); // pass pointer to var
    return 0;
}
💻

Example

This example shows how to pass a pointer to a function to modify the original variable's value.

c
#include <stdio.h>

void updateValue(int *ptr) {
    *ptr = 20; // change value at pointer
}

int main() {
    int num = 10;
    printf("Before: %d\n", num);
    updateValue(&num); // pass pointer to num
    printf("After: %d\n", num);
    return 0;
}
Output
Before: 10 After: 20
⚠️

Common Pitfalls

Common mistakes when passing pointers to functions include:

  • Passing the variable value instead of its address, causing the function to receive a copy, not a pointer.
  • Dereferencing a pointer without initializing it, leading to undefined behavior.
  • Confusing pointer syntax in function declarations and calls.
c
/* Wrong: passing value instead of pointer */
void func(int *ptr) {
    *ptr = 5;
}

int main() {
    int x = 10;
    func(x); // Error: should be func(&x)
    return 0;
}

/* Correct: passing address */
void func(int *ptr) {
    *ptr = 5;
}

int main() {
    int x = 10;
    func(&x); // Correct
    return 0;
}
📊

Quick Reference

ConceptSyntaxDescription
Function parametervoid func(int *ptr)Declare pointer parameter with *
Passing addressfunc(&var)Pass variable address using &
Access value*ptrDereference pointer to get/set value
Pointer variableint *p = &var;Store address in pointer variable

Key Takeaways

Declare function parameters with * to accept pointers.
Pass variable addresses using & when calling the function.
Use * inside the function to access or modify the pointed value.
Always ensure pointers are initialized before dereferencing.
Passing pointers allows functions to modify original variables.