Pointers
Pointers
A pointer is like a map that shows the location of a treasure (the value of a variable). Instead of
carrying the treasure around, you just carry the map (pointer) that shows where to find it.
Key Terms:
#include <stdio.h>
int main() {
int num = 10; // We create a variable 'num' and give it the value
10.
int *ptr; // We create a pointer 'ptr', which will store the
address of a variable.
return 0;
}
Ste Memory
Code Explanation
p (Visualized)
printf("Value of num:
4 The value of num is printed, which is 10. Output: 10
%d\n", num);
printf("Address stored The address stored in ptr is printed. This Output: Address
7
in ptr: %p\n", ptr); address is where num is stored. of num
Memory Visualization:
Memory after Step 1:
num is created with the value 10.
num: 10
Memory after Step 2:
ptr is created, but it's not initialized yet.
num: 10
ptr: (uninitialized)
Memory after Step 3:
ptr is now set to point to the address of num.
num: 10
ptr: Address of num (e.g., 0x7ffee9b08b7c)
Output:
o Value of num = 10
o *: Indicates it is a pointer.
Examples:
int *ptr; // Pointer to an integer
float *temp; // Pointer to a float
Types of Pointers
1. Null Pointer:
o Does not point to any valid memory location.
o Declared as: int *ptr = NULL;
2. Generic Pointer:
o A pointer with void as its data type, meaning it can point to any data
type.
o Declared as: void *ptr;
#include <stdio.h>
int main() {
void *ptr; // Declare a void pointer
return 0;
}
Explanation:
1. void *ptr;
o A void pointer is declared. It can point to any data type but cannot be
directly dereferenced.
2. int num = 42;
o An integer variable num is declared and initialized with the value 42.
3. ptr = #
o The address of num is assigned to the void pointer ptr.
4. *(int *)ptr
o The void pointer is cast to an integer pointer (int *) and then
dereferenced to access the value.
5. ptr = &fnum;
o The address of the float variable fnum is assigned to the void pointer.
6. *(float *)ptr
o The void pointer is cast to a float pointer (float *) and then
dereferenced to access the value.
Output:
Value of integer: 42
Value of float: 3.14
Pointer Initialization
Assign the address of a variable to a pointer during or after declaration.
Syntax:
int a;
int *ptr = &a; // or
ptr = &a;
*a = *b;
o The value of b (pointed to by *b) is assigned to a.
*b = temp;
o The value stored in temp is assigned to b.
void main()
This is the main function where the program starts execution.
Two integers a and b are declared to store user input.
printf and scanf:
printf("Enter values of a and b: ");
o Prompts the user to enter two numbers.
Before Swap:
printf("Before swapping: a = %d, b = %d\n", a, b);
o Prints the values of a and b before the swap.
Call to swap:
swap(&a, &b);
o The memory addresses of a and b are passed to the swap function.