A pointer is a variable that stores the memory address of another variable. Pointers allow for efficient manipulation of data and enable advanced programming techniques like dynamic memory allocation.
data_type *pointer_name;
int *ptr;
Here, ptr
is a pointer to an integer.
Address-of Operator (&
):
Used to get the memory address of a variable.
Example:
int a = 10;
int *ptr = &a; // ptr holds the address of a
Dereference Operator (\*
):
Used to access the value at the address stored in the pointer.
Example:
printf("%d", *ptr); // Outputs: 10
A pointer must be initialized with the address of a variable before it is used.
int a = 5;
int *ptr = &a;
#include <stdio.h>
int main() {
int a = 10;
int *ptr = &a;
printf("Value of a: %d\n", a);
printf("Address of a: %p\n", &a);
printf("Value of ptr: %p\n", ptr);
printf("Value at ptr: %d\n", *ptr);
return 0;
}
A pointer that does not point to any valid memory address.
int *ptr = NULL;
Pointers support arithmetic operations like addition and subtraction.
int arr[3] = {10, 20, 30};
int *ptr = arr;
printf("%d\n", *ptr); // Outputs: 10
printf("%d\n", *(ptr + 1)); // Outputs: 20
printf("%d\n", *(ptr + 2)); // Outputs: 30
The name of an array acts as a pointer to its first element.
Example:
int arr[3] = {10, 20, 30};
int *ptr = arr;
printf("%d\n", ptr[1]); // Outputs: 20
A pointer that stores the address of another pointer.
int a = 10;
int *ptr = &a;
int **pptr = &ptr;
printf("%d\n", **pptr); // Outputs: 10
Pointers are used for dynamic memory allocation using functions like malloc
, calloc
, and free
.
#include <stdlib.h>
#include <stdio.h>
int main() {
int *ptr = (int *)malloc(sizeof(int));
*ptr = 25;
printf("Value: %d\n", *ptr);
free(ptr); // Freeing allocated memory
return 0;
}