Nearby lessons

53 of 72

C - Pointer Introduction

A pointer is a variable that stores the memory address of another variable. In this lesson, you will learn the basic meaning of pointers, how to declare them, and how to get a variable's address.

What Is a Pointer?

A normal variable stores a value. A pointer stores the memory address where another variable is stored.

For example, int *ptr declares a pointer that can store the address of an integer variable.

Example01
CCode Cell
1#include <stdio.h>
2 
3int main()
4{
5 int number = 10;
6 int *ptr = &number;
7 
8 printf("Value: %d\n", number);
9 printf("Pointer stores the address: %p\n", (void *)ptr);
10 
11 return 0;
12}
Output
Value: 10
Pointer stores the address: (memory address)

Memory Address and the & Operator

Every variable has a memory address. Use the & operator to get that address.

Memory addresses can change between program runs, so your output may show a different address.

Example02
CCode Cell
1#include <stdio.h>
2 
3int main()
4{
5 int number = 25;
6 
7 printf("Value: %d\n", number);
8 printf("Address: %p\n", (void *)&number);
9 
10 return 0;
11}
Output
Value: 25
Address: (memory address)

Pointer Declaration and Initialization

Use type *pointerName; to declare a pointer. It is better to give it a valid address when you create it.

Example03
CCode Cell
1#include <stdio.h>
2 
3int main()
4{
5 int number = 50;
6 int *ptr = &number;
7 
8 printf("Value = %d\n", number);
9 printf("Value through pointer = %d\n", *ptr);
10 
11 return 0;
12}
Output
Value = 50
Value through pointer = 50
📝 Key Takeaways
  • A normal variable stores a value.
  • A pointer stores an address.
  • The & operator gives the address of a variable.
  • The * symbol is used when declaring a pointer.
  • Use %p to display an address.

🧠 Test Your Knowledge

2 Questions
Progress: 0 / 2