C Pointers
A pointer is a variable which stores the memory address of another variable. Pointers look hard at first, but they are only addresses. They make C fast and powerful.
Two operators
| Operator | Name | Meaning |
|---|---|---|
& | Address of | Gives the address of a variable |
* | Dereference | Gives the value stored at an address |
Declare and use a pointer
#include <stdio.h>
int main(void) {
int age = 25;
int *p = &age; // p stores the address of age
printf("Value of age: %d\n", age);
printf("Value using pointer: %d\n", *p);
*p = 30; // change age through the pointer
printf("New age: %d\n", age);
return 0;
}
Output:
Output of the above program is
Value of age: 25
Value using pointer: 25
New age: 30
Here int *p means “p is a pointer to an int”. p holds the address, *p is the value at that address.
Printing an address
The address is printed with %p. The real number is different on each run and each computer.
int x = 10;
printf("%p\n", (void *)&x); // prints something like 0x7ffd5c3a1b4c
NULL pointer
A pointer which points to nothing should be set to NULL. Check it before using.
#include <stdio.h>
int main(void) {
int *p = NULL;
if (p == NULL) {
printf("Pointer is empty\n");
}
return 0;
}
Output:
Output of the above program is
Pointer is empty
Why use pointers?
- To change the original value in a function (see call by reference).
- To work with arrays and strings fast.
- To allocate memory while the program runs (dynamic memory).
- To build data structures like linked lists and trees.
Note:
Never use a pointer which has no address. An uninitialized pointer points to a random place, and using it can crash the program. Set it to NULL or give a valid address.
Next: C Pointer Arithmetic.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |