FirstHack Learn
Log in Sign up free
Lessons in this course 0/6 All courses Pointers and Memory in C

First year

Progress0 / 6 lessons
  1. 1. What an address really is
  2. 2. Declaring and dereferencing pointers
  3. 3. Pointers and arrays are not the same thing
  4. 4. Passing by pointer to change a caller variable
  5. 5. malloc, free and what a memory leak costs
  6. 6. Dangling pointers, double free and real crashes

Courses › Pointers and Memory in C

Passing by pointer to change a caller variable

Simulating pass-by-reference in C, returning multiple values, and modifying pointers themselves.

11 min read · Lesson 4 of 6 · Pro

C has only pass-by-value

There is no pass-by-reference in C. Every argument is copied. What people call "pass by reference in C" is really "pass a copy of an address" — and because the copy of the address still points at the original, the function can reach it.

Hold that sentence. It explains everything below.

C
#include <stdio.h>

void broken(int x)   { x = 99; }
void works(int *x)   { *x = 99; }

int main(void)
{
    int a = 1, b = 1;
    broken(a);
    works(&b);
    printf("a = %d, b = %d\n", a, b);   /* a = 1, b = 99 */
    return 0;
}
The rest of this lesson is Pro

The free lessons of Pointers and Memory in C finish what they start — read those first if you have not. This one goes further, and it is part of the paid half.

A pass opens the paid lessons of every course, the mock test papers and the company-wise series. It ends on its own date; nothing renews by itself.

Get a pass — from ₹29 for 7 days

Already bought one? Log in.