How to Use Pointer in C: Syntax, Example, and Common Pitfalls
In C, a
pointer is a variable that stores the memory address of another variable. You declare a pointer using the * symbol and assign it the address of a variable using the & operator. You can access or modify the value at that address by dereferencing the pointer with *.Syntax
To declare a pointer, use the syntax: type *pointerName;. The type specifies the data type the pointer points to. Use & to get the address of a variable and assign it to the pointer. Use * to access the value stored at the pointer's address.
- type: data type of the variable the pointer points to (e.g.,
int). - *pointerName: declares a pointer variable.
- &variable: gets the address of
variable. - *pointer: accesses the value at the pointer's address (dereferencing).
c
int *p; // declares a pointer to int int x = 10; p = &x; // pointer p stores address of x int y = *p; // y gets value at address stored in p (10)
Example
This example shows how to declare a pointer, assign it the address of a variable, and use it to read and change the variable's value.
c
#include <stdio.h> int main() { int num = 5; int *ptr = # // pointer stores address of num printf("Value of num: %d\n", num); // prints 5 printf("Value via pointer: %d\n", *ptr); // prints 5 *ptr = 20; // change value at address pointed by ptr printf("New value of num: %d\n", num); // prints 20 return 0; }
Output
Value of num: 5
Value via pointer: 5
New value of num: 20
Common Pitfalls
Common mistakes when using pointers include:
- Using an uninitialized pointer (it points to random memory).
- Dereferencing a
NULLor invalid pointer causes crashes. - Mixing pointer types can cause incorrect data access.
- Forgetting to use
&when assigning address to pointer.
Always initialize pointers before use and ensure they point to valid memory.
c
#include <stdio.h> int main() { int *p = NULL; // initialize pointer to NULL // printf("%d", *p); // WRONG: dereferencing NULL pointer causes error int x = 10; p = &x; // correct initialization printf("%d", *p); // prints 10 return 0; }
Output
10
Quick Reference
Pointer basics cheat sheet:
| Concept | Description | Example |
|---|---|---|
| Declare pointer | Create a pointer variable | int *p; |
| Get address | Use & to get variable address | p = &x; |
| Dereference | Access value at pointer | int val = *p; |
| Change value | Modify value via pointer | *p = 100; |
| NULL pointer | Pointer with no address | int *p = NULL; |
Key Takeaways
A pointer stores the memory address of a variable using the * symbol.
Use & to assign a variable's address to a pointer and * to access or change the value at that address.
Always initialize pointers before dereferencing to avoid crashes or undefined behavior.
Pointers must match the data type of the variable they point to for correct access.
NULL pointers indicate no valid address and should be checked before use.