c notes pointers
c notes pointers
Pointers are variables that store the memory address of another variable.
Example
#include <stdio.h>
int main() {
int a = 10;
printf("Value of a: %d\n", a);
printf("Address of a: %p\n", (void*)&a);
return 0;
}
Output
Value of a: 10
Address of a: 0x7ffeea9b6d1c (example, will vary)
2. Introduction to Pointers
A pointer is a variable that holds the address of another variable.
Example
Pointers in C 1
#include <stdio.h>
int main() {
int x = 5;
int *ptr = &x; // Pointer ptr stores the address of x
printf("Value of x: %d\n", x);
printf("Address of x: %p\n", (void*)ptr);
printf("Value pointed by ptr: %d\n", *ptr);
return 0;
}
Output
Value of x: 5
Address of x: 0x7ffeea9b6d1c (example, will vary)
Value pointed by ptr: 5
A pointer must be initialized before it can be used, typically with the address
of a variable using the & operator.
Example
#include <stdio.h>
int main() {
float f = 3.14;
float *ptr = &f;
printf("Address of f: %p\n", (void*)&f);
printf("Value of f: %.2f\n", *ptr);
return 0;
}
Output
Pointers in C 2
Address of f: 0x7ffeea9b6d1c (example, will vary)
Value of f: 3.14
locations.
Example
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40};
int *ptr = arr; // Points to the first element
printf("Value at ptr: %d\n", *ptr);
ptr++;
printf("Value after ptr++: %d\n", *ptr);
return 0;
}
Output
Value at ptr: 10
Value after ptr++: 20
Pointers in C 3
Example
#include <stdio.h>
void increment(int *num) {
(*num)++;
}
int main() {
int x = 10;
printf("Before: %d\n", x);
increment(&x);
printf("After: %d\n", x);
return 0;
}
Output
Before: 10
After: 11
Example
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4};
int *ptr = arr;
for (int i = 0; i < 4; i++) {
printf("Element %d: %d\n", i, *(ptr + i));
}
Pointers in C 4
return 0;
}
Output
Element 0: 1
Element 1: 2
Element 2: 3
Element 3: 4
Example
#include <stdio.h>
void doubleArray(int *arr, int size) {
for (int i = 0; i < size; i++) {
arr[i] *= 2;
}
}
int main() {
int arr[] = {1, 2, 3, 4};
int size = 4;
doubleArray(arr, size);
for (int i = 0; i < size; i++) {
printf("Element %d: %d\n", i, arr[i]);
}
return 0;
}
Output
Pointers in C 5
Element 0: 2
Element 1: 4
Element 2: 6
Element 3: 8
0 1
1 2
2 3
3 4
4 5
Step-by-Step Execution
1st Iteration ( i = 0 ):
arr[0] *= 2; → arr[0] = arr[0] * 2; → arr[0] = 1 * 2; → arr[0] = 2
2nd Iteration ( i = 1 ):
arr[1] *= 2; → arr[1] = arr[1] * 2; → arr[1] = 2 * 2; → arr[1] = 4
3rd Iteration ( i = 2 ):
arr[2] *= 2; → arr[2] = arr[2] * 2; → arr[2] = 3 * 2; → arr[2] = 6
Pointers in C 6
4th Iteration ( i = 3 ):
arr[3] *= 2; → arr[3] = arr[3] * 2; → arr[3] = 4 * 2; → arr[3] = 8
5th Iteration ( i = 4 ):
arr[4] *= 2; → arr[4] = arr[4] * 2; → arr[4] = 5 * 2; → arr[4] = 10
Final Output
After the for loop completes, the array is:
2 4 6 8 10
Pointers in C 7