A pointer in C is a variable that stores the memory address of another variable. Instead of holding a value like a regular variable, a pointer holds the location in memory where the value is stored. You can use pointers to access and modify the value of variables indirectly.
For example, if you have a variable x, a pointer can hold the address where x is stored in memory, and you can use the pointer to change or read the value of x.
Concepts of Pointers
Memory Address: Every variable in C is stored in a specific location in memory. A pointer stores the address of this location, rather than the value of the variable itself.
Dereferencing: Dereferencing a pointer means accessing the value stored at the memory address the pointer is pointing to. This is done using the * operator.
Pointer Types: A pointer must be declared with a specific type, as it indicates the type of data the pointer is pointing to. For example, an int* pointer will store the address of an int variable.
Null Pointer: A null pointer is a pointer that doesn’t point to any valid memory address. It is commonly used to indicate that a pointer is not yet assigned a valid memory address. In C, this is typically represented by NULL.
Syntax for Declaring Pointers
To declare a pointer, use the * symbol before the pointer’s name. The type of the pointer must match the type of the variable it will point to
int *ptr; // A pointer to an integer
char *str; // A pointer to a character (string)
Assigning a Pointer
A pointer is assigned the address of a variable using the address-of operator (&).
int num = 20;
int *ptr = # // ptr now holds the address of num
Dereferencing a Pointer
To access the value stored at the address a pointer is pointing to, we use the dereference operator (*).
int value = *ptr; // value is assigned the value stored at the address pointed to by ptr
Example:
#include <stdio.h>
#include <string.h>
int main() {
int num = 20; // Declare an integer variable
int *ptr = # // Declare a pointer to an integer and assign it the address of num
printf("Value of num: %d\n", num); // Directly print the value of num
printf("Address of num: %p\n", &num); // Print the address of num
printf("Value using pointer: %d\n", *ptr); // Dereferencing the pointer to get the value stored at that address
printf("Address stored in pointer: %p\n", ptr); // Print the address stored in the pointer
return 0;
}
Output:
Address of num: 0x7fff5ed09514
Value using pointer: 20
Address stored in pointer: 0x7fff5ed09514