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?
- The memory address of marks
- The value 78
- A copy of marks that updates itself
- 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?
- 6 20
- 5 20
- 6 10
- 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.