C Pointers Introduction
In this page:
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?
#include <stdio.h>
int main() {
int x = 10;
int *ptr = &x;
printf("%d", *ptr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
int main() {
int count = 5;
int *ptr = &count;
printf("%d", *ptr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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 (&)
#include <stdio.h>
int main() {
int count = 5;
int *p = &count;
printf("%p", (void*)p);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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 ()
#include <stdio.h>
int main() {
int x = 5;
int *ptr = &x;
*ptr = 10;
printf("%d", x);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
int main() {
int *ptr = NULL;
if (ptr != NULL) {
printf("%d", *ptr);
} else {
printf("Pointer is null");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: