What is a pointer?
- C course
- Beginner
- Lesson 71/116
- 5 min
Learn that a pointer holds a memory address and is accessed with *.
What is a pointer?
A pointer is a variable that holds a memory address. The declaration int *ptr says ptr will hold the address of an int.
int x = 42;
int *ptr = &x; /* & takes the address */
printf("%d\n", *ptr); /* * accesses the value, prints 42 */A pointer stores the memory address of a variable, not the variable itself. We will cover & and * in detail in the next lessons.
Pointer declaration syntax
A pointer declaration writes the type, the asterisk and the name together. The asterisk marks the variable as a pointer.
int *ip; /* int pointer */
double *dp; /* double pointer */
char *cp; /* char pointer */The pointer type depends on the type of the variable it points to. int * and char * are different types; they cannot be assigned to each other directly.
Practice Access a value via a pointer
Define int x = 42;. Bind ptr to x with int *ptr = &x;. Print the value ptr points to with printf("%d\n", *ptr);. Output should be 42.
Starter code
#include <stdio.h>
int main(void) {
int x = 42;
/* bind ptr to x */
/* print *ptr with printf %d */
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
int x = 42;
int *ptr = &x;
printf("%d\n", *ptr);
return 0;
}Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does int *ptr declare?
- ptr is an int value
- ptr is a constant
- ptr is a char
- ptr holds the address of an int Correct answer
Explanation: int *ptr declares that ptr holds the address of an int.
2 int pointer declaration
int ____ptr; /* int pointer */
int *ptr; /* int pointer */
Explanation: The asterisk marks a pointer.
3 Match pointer types
| Term | Meaning |
|---|---|
int * |
int pointer |
char * |
char pointer |
double * |
double pointer |
void * |
generic pointer |