On this page (14 sections)
- 🎯 Why Do We Need Pointers?
- 1️⃣ Memory and Addresses
- 2️⃣ What Is a Pointer?
- 3️⃣ Declaring and Initializing a Pointer
- 4️⃣ A Pointer Type Must Match the Data Type
- 5️⃣ How Big Is a Pointer?
- 6️⃣ Start Safe: the NULL Pointer
- 7️⃣ Pointing at a Different Variable
- 8️⃣ Two Pointers, One Variable
- 9️⃣ The int *p, q Trap
- 🔟 Initializing with an Array Name
- ⚠️ Common Mistakes
- ❓ Frequently Asked Questions
- ✅ Key Takeaways
Module III · Pointers · Pointer Declaration and Initialization
🎯 Why Do We Need Pointers?
Think of a big hostel with hundreds of rooms. If you want to meet a friend, you do not carry the friend with you. You only need the room number. With the room number, you can go to the room, see what is inside and even change it.
A computer’s memory works the same way. Every variable lives in a numbered place. In C, a pointer is a variable that keeps such a number, so a program can reach a variable indirectly. Pointers let functions change the caller’s variables, let programs work with arrays and strings efficiently and let us ask the system for memory while the program runs.
A pointer is a variable that stores the address of another variable. This lecture teaches the first step: how to declare a pointer and how to initialize it safely.
ptr1004marks85Figure 1: The pointer ptr stores the address 1004. That is the address of marks, so we say ptr points to marks.
1️⃣ Memory and Addresses
Memory is a long row of small cells called bytes. Each byte has its own number, called its address. A variable of type int usually takes 4 bytes, and its address is the address of its first byte.
20age85marks7x12yFigure 2: Every variable sits in memory at an address. The addresses here (1000, 1004, …) are simplified for teaching; real addresses are much larger and change on every run.
The address-of operator & gives the address of a variable. To print an address, use the %p format and convert it to (void *).
Program 1: Printing the value and the address of a variable
#include <stdio.h>
int main(void) {
int age = 20;
printf("Value of age : %d\n", age);
printf("Address of age : %p\n", (void *)&age);
return 0;
}
Value of age : 20
Address of age : 0x7ffccb1cc424
ageis a normalintthat holds 20.&ageis the address whereageis stored.%pprints an address, usually in hexadecimal form (starting with0x).
2️⃣ What Is a Pointer?
An address is just a number, but a plain int is not a good place to keep it. C wants to know what kind of data lives at that address, so that it can read it correctly. A pointer therefore has a type: it is a "pointer to int", a "pointer to char" and so on.
| Item | Ordinary variable | Pointer variable |
|---|---|---|
| Stores | A value, such as 85 | The address of another variable |
| Example | int marks = 85; | int *ptr = &marks; |
| Symbol in the declaration | None | * before the name |
3️⃣ Declaring and Initializing a Pointer
The general form is:
data_type *pointer_name; /* declaration */
data_type *pointer_name = &variable; /* declaration with initialization */
The * in a declaration means "this name is a pointer". The pointer and the variable it points to must have the same data type.
Program 2: Declaring and initializing a pointer
#include <stdio.h>
int main(void) {
int marks = 85;
int *ptr = &marks;
printf("marks = %d\n", marks);
printf("*ptr = %d\n", *ptr);
printf("ptr == &marks: %s\n", (ptr == &marks) ? "yes" : "no");
return 0;
}
marks = 85
*ptr = 85
ptr == &marks: yes
int marks = 85;creates a normal variable holding 85.int *ptr = &marks;creates a pointer tointand stores the address ofmarksin it.*ptrmeans "the value stored at the address in ptr". This is called dereferencing. It gives 85.ptr == &marksis true, because ptr holds exactly the address of marks.
int *ptr), the star says "this is a pointer". In an expression (*ptr), the star says "go to that address and get the value". Lecture 36 explains dereferencing in detail.4️⃣ A Pointer Type Must Match the Data Type
Each basic data type has its own kind of pointer. The pointer type tells C how many bytes to read and how to understand them.
| Variable | Pointer declaration | Read as |
|---|---|---|
int n | int *pi | pointer to int |
float f | float *pf | pointer to float |
char ch | char *pc | pointer to char |
double d | double *pd | pointer to double |
Program 3: Pointers of different types
#include <stdio.h>
int main(void) {
int n = 7;
float f = 2.5f;
char ch = 'A';
double d = 9.75;
int *pi = &n;
float *pf = &f;
char *pc = &ch;
double *pd = &d;
printf("*pi = %d\n", *pi);
printf("*pf = %.1f\n", *pf);
printf("*pc = %c\n", *pc);
printf("*pd = %.2f\n", *pd);
return 0;
}
*pi = 7
*pf = 2.5
*pc = A
*pd = 9.75
- Each pointer is initialized with the address of a variable of its own type.
*pi,*pf,*pcand*pdgive back the original values 7, 2.5, ‘A’ and 9.75.- If you wrote
float *p = &n;(a float pointer holding the address of an int), the compiler would warn you about the mismatch.
5️⃣ How Big Is a Pointer?
All pointers store an address, so they are all the same size on a given computer, whatever they point to. Only the type of the target changes.
Program 4: Size of different pointers
#include <stdio.h>
int main(void) {
int *pi;
char *pc;
double *pd;
printf("Size of int * : %zu bytes\n", sizeof(pi));
printf("Size of char * : %zu bytes\n", sizeof(pc));
printf("Size of double * : %zu bytes\n", sizeof(pd));
printf("Size of int : %zu bytes\n", sizeof(int));
printf("Size of double : %zu bytes\n", sizeof(double));
return 0;
}
Size of int * : 8 bytes
Size of char * : 8 bytes
Size of double * : 8 bytes
Size of int : 4 bytes
Size of double : 8 bytes
- The three pointers are declared but not used, and that is fine, because
sizeofonly needs their type. - On this 64-bit computer every pointer takes 8 bytes. On an older 32-bit system it would be 4 bytes.
%zuis the correct format for the result ofsizeof.- Notice that a
double *is 8 bytes and adoubleis also 8 bytes, but achar *is still 8 bytes. A pointer’s size does not depend on its target.
6️⃣ Start Safe: the NULL Pointer
A pointer that is declared but never given a value holds some leftover garbage address. Such a pointer is called a wild pointer, and using it can crash the program. The safe habit is: always initialize a pointer, either with the address of a real variable or with NULL.
NULL is a special value that means "this pointer points to nothing". It is defined in <stdio.h> and in <stdlib.h>.
Not initialized.
Holds a garbage address.
❌ Using
*p is dangerous.Clearly points nowhere.
Easy to test with
p == NULL.✅ Safe starting value.
Figure 3: An uninitialized pointer is a wild pointer. A NULL pointer is a pointer that is known to point nowhere.
Program 5: Using NULL to mark an empty pointer
#include <stdio.h>
int main(void) {
int *p = NULL;
int value = 42;
if (p == NULL) {
printf("p is NULL: it points nowhere yet.\n");
}
p = &value;
if (p != NULL) {
printf("p now points to value, which holds %d.\n", *p);
}
return 0;
}
p is NULL: it points nowhere yet.
p now points to value, which holds 42.
int *p = NULL;creates a pointer that points nowhere.- The first
ifis true, so the first message is printed. p = &value;gives the pointer a real target.- Now
p != NULLis true, and*psafely gives 42.
*p while p is NULL stops the program with an error. Check p != NULL before you use it.7️⃣ Pointing at a Different Variable
A pointer is an ordinary variable, so you can change what it holds. It can point to a now and to b later, as long as both have the right type.
Program 6: Re-pointing a pointer
#include <stdio.h>
int main(void) {
int a = 10, b = 20;
int *p = &a;
printf("p points to a: *p = %d\n", *p);
p = &b;
printf("p points to b: *p = %d\n", *p);
*p = 99;
printf("After *p = 99: a = %d, b = %d\n", a, b);
return 0;
}
p points to a: *p = 10
p points to b: *p = 20
After *p = 99: a = 10, b = 99
p = &a;a = 10b = 20p = &b;a = 10b = 20Figure 4: A pointer can be re-pointed. The green box is the variable that p points to at that moment.
| Statement | p points to | a | b |
|---|---|---|---|
int *p = &a; | a | 10 | 20 |
p = &b; | b | 10 | 20 |
*p = 99; | b | 10 | 99 |
- At first
*preadsa, so it prints 10. - After
p = &b;the pointer holds the address ofb, so*preads 20. Note that there is no star on the left side here: we change the pointer, not the value. *p = 99;has a star, so it changes the value at the target. Onlybchanges. The variableastays 10.
8️⃣ Two Pointers, One Variable
More than one pointer can hold the same address. They are like two keys to the same locker.
Program 7: Two pointers sharing one variable
#include <stdio.h>
int main(void) {
int x = 5;
int *p1 = &x;
int *p2 = p1;
printf("*p1 = %d, *p2 = %d\n", *p1, *p2);
printf("p1 == p2: %s\n", (p1 == p2) ? "yes" : "no");
*p2 = 50;
printf("After *p2 = 50: x = %d, *p1 = %d\n", x, *p1);
return 0;
}
*p1 = 5, *p2 = 5
p1 == p2: yes
After *p2 = 50: x = 50, *p1 = 50
p1 | ⟶ ⟶ | x5 → 50 |
p2 |
Figure 5: Two pointers can hold the same address. A change made through either one is seen in x.
| Statement | x | *p1 | *p2 |
|---|---|---|---|
int *p2 = p1; (after p1 = &x) | 5 | 5 | 5 |
*p2 = 50; | 50 | 50 | 50 |
int *p2 = p1;copies the address stored in p1 into p2. Now both point tox.p1 == p2is true because both hold the same address.- Changing the value through
p2changesx, and so*p1shows 50 too. There is only one box; there are two ways to reach it.
9️⃣ The int *p, q Trap
When you declare several variables in one line, the star belongs to one name only, not to the whole line.
Program 8: Which names are pointers?
#include <stdio.h>
int main(void) {
int *p, q;
int *r, *s;
int x = 3;
p = &x;
q = 8;
r = &x;
s = &x;
printf("sizeof(p) = %zu, sizeof(q) = %zu\n", sizeof(p), sizeof(q));
printf("*p = %d, q = %d, *r = %d, *s = %d\n", *p, q, *r, *s);
return 0;
}
sizeof(p) = 8, sizeof(q) = 4
*p = 3, q = 8, *r = 3, *s = 3
int *p, q;makespa pointer, butqis a plainint. That is whysizeof(q)is 4 andsizeof(p)is 8.int *r, *s;needs a star before each name to make both pointers.- To avoid confusion, declare pointers on separate lines.
🔟 Initializing with an Array Name
An array name stands for the address of its first element. So an array name can be stored in a pointer of the same type, without using &.
Program 9: A pointer that holds an array name
#include <stdio.h>
int main(void) {
int arr[4] = {10, 20, 30, 40};
int *p = arr;
printf("p = arr -> *p = %d\n", *p);
printf("p == &arr[0] : %s\n", (p == &arr[0]) ? "yes" : "no");
long gap = (char *)&arr[1] - (char *)&arr[0];
printf("Gap between arr[0] and arr[1]: %ld bytes\n", gap);
return 0;
}
p = arr -> *p = 10
p == &arr[0] : yes
Gap between arr[0] and arr[1]: 4 bytes
int *p = arr;stores the address ofarr[0]. Both*pandarr[0]give 10.p == &arr[0]is true, which proves thatarrand&arr[0]mean the same address.- The two elements are 4 bytes apart because each
inttakes 4 bytes. Lecture 37 uses this fact for pointer arithmetic.
⚠️ Common Mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
int *p; *p = 10; | p is uninitialized (a wild pointer), so the write goes to a random place | Point p at a real variable first, or start with NULL |
int *p = 10; | A plain number is not an address of an int | int *p = &x; |
int x; float *p = &x; | The pointer type does not match the variable type | Use int *p for an int |
int *p, q; and expecting two pointers | Only p is a pointer | int *p, *q; |
Using *p when p is NULL | There is no target to read | Test if (p != NULL) first |
Writing p = x; instead of p = &x; | x is a value, not an address | Use the address-of operator & |
| Printing addresses and expecting the same numbers every run | The system may place variables elsewhere each time | Print values, not addresses, in your logic |
❓ Frequently Asked Questions
Q1. Why does a pointer need a data type?
The address alone does not say how many bytes to read or how to read them. The type int * tells C to read 4 bytes as an integer; char * tells it to read 1 byte as a character.
Q2. Where do I write the star: int* p, int *p or int * p?
All three mean the same thing. Writing int *p is common because the star really belongs to the name, as the int *p, q; trap shows.
Q3. Does a pointer to int hold an int?
No. It holds the address of an int. The int itself lives elsewhere, and *p reaches it.
Q4. Can a pointer point to another pointer?
Yes. That is a pointer to pointer, which Lecture 38 covers.
✅ Key Takeaways
- Every variable has an address. The
&operator gives it. - A pointer is a variable that stores the address of another variable.
- Declare a pointer with a star:
int *ptr;. The pointer type must match the data type of its target. - Initialize a pointer with an address:
int *ptr = &marks;. - Use
*ptrto get the value at that address. - All pointers on one computer have the same size, whatever they point to.
- Never leave a pointer uninitialized. Use
NULLwhen you have no target yet, and check for it before dereferencing. - In
int *p, q;onlypis a pointer. - Printed addresses change from run to run and from computer to computer.
🎓 Practice questions: (1) Declare anint, afloatand acharvariable, create a pointer for each and print the values through the pointers. (2) Write a program withint a = 4, b = 9;and a pointer that first points toa, then tob. Print*peach time. (3) Declareint *p, q;and printsizeofof both. Explain the result. (4) Create two pointers to one variable, change the value through one of them and show that the other sees the change. (5) Declare a pointer asNULL, test it withif, then point it to a variable and print the value.
All 29 lessons in this series (open course page)
Part 1 · Getting Started
- Lesson 1: Introduction to C Programming: Overview, Features and Applications
- Lesson 2: The Structure of a C Program: Building Your First Blueprint
- Lesson 3: Identifiers, Keywords and Variables: Naming Things in C Programming
- Lesson 4: Introduction to Algorithms: Thinking Before You Code
- Lesson 5: Introduction to Flowcharts: Drawing the Logic You Already Know
Part 2 · Data Types, Input/Output and Operators
- Lesson 6: Data Types in C: Choosing the Right Box for Every Value
- Lesson 7: Formatted Input and Output in C: Taking Control of printf and scanf
- Lesson 8: Practice Exercise Sheet: Data Types in C
- Lesson 9: Operators and Expressions in C: Assignment, Unary, and Arithmetic
- Lesson 10: Relational, Logical, and Conditional Operators in C
- Lesson 11: Bitwise and Special Operators in C
- Lesson 12: Operator Precedence and Associativity in C
Part 3 · Decisions and Loops
- Lesson 13: Decision and Case Control: if and if-else in C
- Lesson 14: The switch Statement — and switch vs. if-else Ladder
- Lesson 15: The for Loop: Definite Repetition in C
- Lesson 16: while and do-while Loops: Indefinite Repetition in C
- Lesson 17: break and continue in C: Controlling a Loop from the Inside
- Lesson 18: The goto Statement in C: Jumping Around Your Program
Part 4 · Arrays
- Lesson 19: 1-D Arrays in C: Declaration, Address Calculation, Insertion and Deletion
- Lesson 20: Two-Dimensional Arrays in C: Declaration, Initialization and Accessing Elements
- Lesson 21: Matrix Addition and Matrix Multiplication in C
Part 5 · Strings
- Lesson 22: Strings in C: Working with Character Arrays
- Lesson 23: 1-D and 2-D Character Arrays in C: Storing Names and Words
Part 6 · Functions and Scope
- Lesson 24: Functions in C: Declaration and Definition
- Lesson 25: Categories of Functions in C
- Lesson 26: Scope of Variables in C
- Lesson 27: Call by Value in C: How Parameter Passing Works
- Lesson 28: Passing Arrays to Functions in C: Search, Sum and Sort