← Back to C Course | Chapter 7: Pointers | Lesson 2 of 9

C Pointers Introduction

What is a Pointer?

This indirection is the foundation of dynamic memory, arrays, and passing large data efficiently between functions -- instead of copying a whole struct or array, you can pass just its address, which is always a fixed, small size.

Example: What is a Pointer?

c
#include <stdio.h>
int main() {
	int x = 10;
	int *ptr = &x;
	printf("%d", *ptr);
	return 0;
}

Declaring Pointers

int *ptr declares ptr as 'pointer to int', meaning it can only validly hold the address of an int variable; assigning it the address of a float or char variable will compile with a warning but produce incorrect behavior later.

Example: Declaring Pointers

c
#include <stdio.h>
int main() {
	int count = 5;
	int *ptr = &count;
	printf("%d", *ptr);
	return 0;
}

The Address-Of Operator (&)

Writing &count gives you the address where count actually lives in memory, which you then typically assign to a pointer variable, e.g. int *p = &count -- this is the operation you use to connect a pointer to a real variable.

Example: The Address-Of Operator (&)

c
#include <stdio.h>
int main() {
	int count = 5;
	int *p = &count;
	printf("%p", (void*)p);
	return 0;
}

The Dereferencing Operator ()

*ptr = 10 doesn't change ptr itself; it changes the value stored at the address ptr is currently pointing to -- this distinction between changing a pointer and changing what it points to is one of the trickiest parts of learning pointers.

Example: The Dereferencing Operator ()

c
#include <stdio.h>
int main() {
	int x = 5;
	int *ptr = &x;
	*ptr = 10;
	printf("%d", x);
	return 0;
}

Null Pointers

Dereferencing a NULL pointer (writing *ptr when ptr is NULL) is one of the most common causes of a program crash (segmentation fault), so checking if (ptr != NULL) before dereferencing is a standard defensive habit.

Example: Null Pointers

c
#include <stdio.h>
int main() {
	int *ptr = NULL;
	if (ptr != NULL) {
		printf("%d", *ptr);
	} else {
		printf("Pointer is null");
	}
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.