In C, why do we often use pointers to pass variables to functions?
Think about how functions can change variables outside their own scope.
Passing a pointer lets the function access and change the original variable's memory location, so changes affect the original.
What is the output of this C program?
#include <stdio.h> void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } int main() { int x = 5, y = 10; swap(&x, &y); printf("x = %d, y = %d", x, y); return 0; }
Look at how the swap function uses pointers to change values.
The swap function uses pointers to exchange the values of x and y by accessing their memory addresses.
What will this C code print?
#include <stdio.h> int main() { int arr[] = {1, 2, 3, 4}; int *p = arr; printf("%d", *(p + 2)); return 0; }
Remember that pointer arithmetic moves by the size of the data type.
Adding 2 to pointer p moves it to the third element (index 2) of the array, which is 3.
What error does this code cause?
#include <stdio.h> int main() { int *p; *p = 10; printf("%d", *p); return 0; }
Think about what happens when you use a pointer that does not point to valid memory.
The pointer p is uninitialized and points to an unknown location, so dereferencing it causes a segmentation fault.
Why are pointers necessary when working with dynamic memory allocation in C?
Consider how malloc returns memory and how you access it.
Dynamic memory functions return pointers to memory blocks, which you must use to access and manage that memory.