Summary - Pointer basics
- C course
- Beginner
- Lesson 76/116
- 5 min
Combine &, * and NULL to write a swap function.
Summary: Pointer basics
In this group you saw the basics of pointers. A pointer holds a memory address; & takes the address, * accesses the value.
int *ptr: int pointer declaration&x: x's address*ptr: the value ptr points toNULL: null pointer; safe starting pointptr + 1: jumps to the next element
Now let's combine these in one task.
Practice Read and print a value via a pointer
Define int x = 15;. Bind with int *ptr = &x;. Print the value ptr points to with printf("%d\n", *ptr);. Output should be 15.
Starter code
#include <stdio.h>
int main(void) {
int x = 15;
/* bind ptr to x */
/* print *ptr with printf %d */
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
int x = 15;
int *ptr = &x;
printf("%d\n", *ptr);
return 0;
}Expected output
15
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which operator gives a variable's address?
- & Correct answer
- *
- +
- -
Explanation: Answer is &. The & operator takes a variable's address.
2 NULL check
int *p = NULL;
if (p ____) { /* not safe */ }
int *p = NULL;
if (p == NULL) { /* not safe */ }
Explanation: p == NULL checks for null.
3 Match pointer concepts
| Term | Meaning |
|---|---|
& |
takes address |
* |
dereferences |
NULL |
null pointer |
ptr + 1 |
next element |