Skip to content
StudyFame

Pointers and Functions in C

Functions and pointers work together in two directions. You can send a pointer into a function so it can change your variables, and a function can send a pointer back to you as its return value.

In this lesson you will practise both directions, write the classic swap with pointers, return a pointer to the largest element of an array, and learn the one rule that prevents a famous bug: never return the address of a local variable.

What You Will Learn

  • How to pass pointers to a function.
  • Why pointer parameters let a function change the caller's data.
  • How to return a pointer from a function.
  • Which pointers are safe to return.
  • Why returning a local variable's address is a bug.

Pointers and Functions Explained

Exam definition: Passing a pointer to a function sends the address of a variable, so the function can read and modify the original through * (call by reference). A function returning a pointer has a return type like int * and gives back an address; that address must stay valid after the function ends.

Memory trick: Returning a local variable's address is like giving a friend the room number of a hotel you are checking out of. When they reach it, the room belongs to someone else. Return only addresses that outlive the function.

Syntax: Pointer Parameters and Pointer Return Types

/* pointer parameters */
void swap(int *a, int *b);          /* call: swap(&x, &y); */
void fill(int *arr, int n);         /* call: fill(marks, 5); */

/* returning a pointer */
int  *largest(int *arr, int n);     /* returns an address inside arr */
char *grade_name(int marks);        /* returns a pointer to a string */
Returning…Safe?Why
Address inside an array the caller passedYesThe caller's array still exists
A string literal (return "Pass";)YesLiterals live for the whole program
Address of a static local variableYesStatic variables are never destroyed
Memory from mallocYesLives until free (Module 12)
Address of a normal local variableNoDestroyed when the function returns: dangling pointer

Example 1: Swap and Update Using Pointer Parameters

#include <stdio.h>

void swap(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

void apply_discount(float *price, float percent)
{
    *price = *price - (*price * percent / 100);
}

int main(void)
{
    int x = 5, y = 8;
    float shoes = 2000.0f;

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

    apply_discount(&shoes, 15);
    printf("Shoes after 15%% off: %.2f\n", shoes);

    return 0;
}

Output

After swap: x = 8, y = 5
Shoes after 15% off: 1700.00

Code Explanation

  1. swap(&x, &y) passes the addresses of x and y. Inside, a points to x and b points to y.
  2. *a = *b; writes y's value into x itself. The three-step swap with temp exchanges the originals.
  3. apply_discount changes shoes in main through *price. No return value is needed.
  4. %% inside printf prints a single % sign.

Also see swapping of two numbers using pointer.

How Returning a Pointer Works

A function can return an address so the caller can reach (and even change) that data directly. For example, a function can return a pointer to the largest element: the caller then knows both its value and its position, and can modify it.

marks:  [ 67 | 91 | 78 | 85 ]
                ^
                largest(marks, 4) returns this address
caller:  *best = 100;   ->  marks becomes [ 67 | 100 | 78 | 85 ]

Example 2: Functions That Return Pointers (Safely)

#include <stdio.h>

int *largest(int *arr, int n)          /* returns an address inside arr */
{
    int *best = arr;
    int i;
    for (i = 1; i < n; i++)
    {
        if (arr[i] > *best)
            best = &arr[i];
    }
    return best;
}

const char *grade_name(int marks)      /* returns a string literal */
{
    if (marks >= 90) return "Outstanding";
    if (marks >= 75) return "Distinction";
    if (marks >= 40) return "Pass";
    return "Fail";
}

int *next_token(void)                  /* returns a static local */
{
    static int token = 100;            /* survives between calls */
    token++;
    return &token;
}

int main(void)
{
    int marks[] = {67, 91, 78, 85};
    int *best = largest(marks, 4);

    printf("Highest: %d at index %d (%s)\n", *best, (int)(best - marks), grade_name(*best));

    *best = 100;                       /* change it through the pointer */
    printf("After update marks[1] = %d\n", marks[1]);

    printf("Token: %d\n", *next_token());
    printf("Token: %d\n", *next_token());

    return 0;
}

Output

Highest: 91 at index 1 (Outstanding)
After update marks[1] = 100
Token: 101
Token: 102
  • largest returns &arr[i]: an address inside the caller's array, which still exists after the call.
  • best - marks converts the returned pointer into an index.
  • grade_name returns string literals, which live for the whole program. Its return type is const char * because literals are read-only.
  • static int token is created once and keeps its value, so returning its address is safe.

The wrong way: returning a local address

int *bad(void)
{
    int result = 42;      /* local: destroyed when bad() returns */
    return &result;       /* compiler warning: address of local variable */
}
/* int *p = bad(); printf("%d", *p);  -> garbage or crash (dangling pointer) */

Important Points to Remember

  • Pass &variable when a function must change it.
  • In the function, use *param to read or write the original.
  • Return type int * means the function returns an address.
  • Safe to return: caller's array element, string literal, static variable, malloc memory.
  • Never return the address of a normal local variable.
  • Use const on pointer parameters that are only read.

Common Mistakes Beginners Make

MistakeWhat happensFix
swap(x, y) for swap(int *, int *)Warning, crashswap(&x, &y)
Returning &localDangling pointer: garbageUse static, malloc, or a caller's array
a = b inside swap instead of *a = *bOnly local pointer copies changeUse *
Returning a local array: char s[20]; return s;Dangling pointerLet the caller pass the buffer
Not checking a returned pointer for NULLCrash when nothing was foundif (p != NULL)

Pointers and Functions Practice Questions

  1. Why must we pass &x to a function that changes x?
  2. Write the prototype of a function that returns a pointer to a char.
  3. Why is returning the address of a local variable wrong?
  4. Name three kinds of addresses that are safe to return.
  5. In Example 2, how does the caller find the index of the largest element?
Show answers
  1. The function needs the address to reach and modify the original variable; otherwise it gets only a copy.
  2. char *f(void); (with any parameters).
  3. The local variable is destroyed when the function returns, so the pointer becomes dangling.
  4. An element of an array passed by the caller, a string literal, a static variable (also malloc memory).
  5. By pointer subtraction: best - marks.

Coding Exercise

Write int *find(int *arr, int n, int key) that returns a pointer to the first element equal to key, or NULL if not found. Use it to change the 30 in {10, 20, 30, 40} to 35.

Show solution
#include <stdio.h>

int *find(int *arr, int n, int key)
{
    int i;
    for (i = 0; i < n; i++)
        if (arr[i] == key)
            return &arr[i];
    return NULL;
}

int main(void)
{
    int a[] = {10, 20, 30, 40};
    int *p = find(a, 4, 30);
    int i;

    if (p != NULL)
        *p = 35;
    if (find(a, 4, 99) == NULL)
        printf("99 not found\n");

    for (i = 0; i < 4; i++)
        printf("%d ", a[i]);
    printf("\n");
    return 0;
}
99 not found
10 20 35 40

Quick Quiz: Pointers and Functions (MCQ)

  1. To let void inc(int *n) change x, call:

    A) inc(x);   B) inc(&x);   C) inc(*x);   D) inc(**x);

  2. float *f(void); declares a function that returns:

    A) A float   B) A pointer to float   C) Nothing   D) A float array

  3. Which is unsafe to return?

    A) "Hello"   B) Address of a static variable   C) Address of a local variable   D) Address of a caller's array element

  4. A pointer to memory that no longer exists is called:

    A) NULL pointer   B) Void pointer   C) Dangling pointer   D) Function pointer

  5. Inside swap(int *a, int *b), which line puts b's value into a's variable?

    A) a = b;   B) *a = *b;   C) &a = &b;   D) a = *b;

Show answers
  1. B: inc(&x);
  2. B: a pointer to float.
  3. C: address of a local variable.
  4. C: dangling pointer.
  5. B: *a = *b;

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

Change caller's variablePass &x, use *p
Swapswap(&x, &y) with *a = *b
int *f()Returns an address
Safe to returnCaller's data, literal, static, malloc
Never return&local variable
Result of that bugDangling pointer

Frequently asked questions

How do you pass a pointer to a function?
Declare a pointer parameter (int *p) and call with the address (f(&x)).
Can a function return a pointer?
Yes, as long as the address stays valid: not the address of a local variable.
Why is returning a local variable's address dangerous?
Locals are destroyed when the function returns, leaving a dangling pointer.

Remember

  • Pointer in = function can change your data.
  • Pointer out = only if it outlives the function (no hotel rooms!).

Next Topic

Next lesson: Double Pointers in C. You will meet a pointer that stores the address of another pointer.