Concepts of Pointers

A pointer is a variable that stores another variable's address: & asks where a variable lives, and * reaches the value living there.

5 min read · 9 cards · 4 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

Who changed marks?

Three lines:

int marks = 78;

int *p = &marks;

*p = 99;

No line assigns to marks directly. What is marks now?

Think first

Your guess first

Type the value you think marks holds.

Show the answer

99. p holds the address of marks, so *p is marks itself, reached by another route. Writing to *p wrote to marks.

Theory

Address and value

Every variable lives at a numbered memory address. A pointer is a variable that stores an address: int *p reads as "p points to an int". &, the address-of operator, gives marks's address as &marks, and *, the dereference (value-at) operator, gives the value at the address p holds as *p.

Quiz

After int marks = 78; int *p = &marks;, what is stored inside p?

  1. The memory address of marks
  2. The value 78
  3. A copy of marks that updates itself
  4. The name marks as text
Show the answer

The memory address of marks

p holds where marks lives, not what it holds. 78 is what you get when you dereference it, *p. Mixing up the pointer with the value it points at is the classic slip.

Think first

The scanf mystery

Why does scanf("%d", &marks) need the &? Type your reason.

Show the answer

scanf has to store the number in your variable, so it needs to know where marks lives. Plain marks would hand it the value 78, which is useless for delivery. The & you have written since Unit 1 was an address all along, and the same trick lets functions change your variables.

Watch out

One star, two jobs

In a declaration, int *p makes p a pointer. In an expression, *p fetches the value p points at, so p is the address and *p is the value.

Practical

Exam-style: predict the output

#include <stdio.h>

int main() {
    int a = 5, b = 10;
    int *p = &a;

    *p = *p + 1;
    p = &b;
    *p = *p * 2;

    printf("%d %d", a, b);
    return 0;
}

This example runs in Gri-Learn on the web, where you can edit it and see the output.

Quiz

Exam-style: what is the output of the program above?

  1. 6 20
  2. 5 20
  3. 6 10
  4. 12 10
Show the answer

6 20

p first points at a, so *p = *p + 1 makes a 6. Then p moves to b, and *p = *p * 2 makes b 20. Moving p changes where it points; it never changes a.

Summary

Key takeaways

  • A pointer stores an address, not a value.
  • & gives a variable's address; * reaches the value at an address.
  • Writing through *p changes the variable p points at.
  • Memory hook: & asks where, * asks what.

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Concepts of Arrays and Pointer

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati