pointer_exercises
pointer_exercises
#include <stdio.h>
int main() {
int x = 10;
int *ptr = &x;
return 0;
}
#include <stdio.h>
int main() {
int num = 10;
printf("Before: %d\n", num);
modifyValue(&num);
printf("After: %d\n", num);
return 0;
}
#include <stdio.h>
int main() {
int x = 5, y = 10;
printf("Before swap: x=%d, y=%d\n", x, y);
swap(&x, &y);
printf("After swap: x=%d, y=%d\n", x, y);
return 0;
}
#include <stdio.h>
int main() {
int x = 10;
int *ptr = &x;
int **pptr = &ptr;
return 0;
}
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int *ptr = arr;
return 0;
}
6. Find Largest Element in an Array Using Pointers
Problem: Find the maximum element in an array.
#include <stdio.h>
int main() {
int numbers[] = {3, 7, 2, 8, 5};
printf("Max element: %d\n", findMax(numbers, 5));
return 0;
}
7. Array of Pointers
Problem: Store values using an array of pointers.
#include <stdio.h>
int main() {
int a = 10, b = 20, c = 30;
int *arr[] = {&a, &b, &c};
return 0;
}
#include <stdio.h>
int main() {
char *names[] = {"Alice", "Bob", "Charlie"};
return 0;
}
#include <stdio.h>
#include <string.h>
int main() {
char *words[] = {"banana", "apple", "cherry"};
int n = 3;
sortStrings(words, n);
return 0;
}
#include <stdio.h>
int main() {
int numbers[] = {10, 20, 30, 40, 50};
int *ptrArray[5];
for (int i = 0; i < 5; i++) {
ptrArray[i] = &numbers[i];
}
return 0;
}
#include <stdio.h>
int main() {
int numbers[10] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50};
int *ptrArray[5];
ptrArray[0] = &numbers[0];
ptrArray[1] = &numbers[2];
ptrArray[2] = &numbers[4];
ptrArray[3] = &numbers[6];
ptrArray[4] = &numbers[8];
return 0;
}
Conclusion
These exercises cover fundamental pointer concepts in C, including:
Pointer basics
Pointer arithmetic
Double pointers
Arrays and pointers
Sorting with pointers