Sure! Let's talk about pointers in C using simple language
A pointer in C is a special type of variable that stores the memory address of another variable. Think of it like a label that tells you where something is stored in memory.
To declare a pointer, you use the '*'symbol before the variable name. For example:
int *ptr;
This declares a pointer variable ptr
that can store the memory address of an integer.
You can assign the memory address of a variable to a pointer using the address-of operator &
. For example:
int x = 10;
int *ptr = &x;
This assigns the memory address of variable x
to the pointer ptr
.
You can access the value stored at a memory address using the dereference operator *
. For example:
int x = 10;
int *ptr = &x;
printf("The value of x is: %d\n", *ptr);
This will print the value of x
, which is 10
, because ptr
stores the memory address of x
, and *ptr
accesses the value stored at that memory address.
Let's say we have a program that swaps the values of two variables using pointers:
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 5, y = 10;
printf("Before swapping: x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("After swapping: x = %d, y = %d\n", x, y);
return 0;
}
In this example
swap
that takes two pointers as arguments.swap
function, we use pointer dereferencing to swap the values stored at the memory addresses pointed to by a
and b
.main
function, we declare two variables x
and y
.swap
function and pass the memory addresses of x
and y
as arguments.x
and y
to see the result.