What is the output of this C code snippet?
#include <stdio.h> int main() { int arr[] = {10, 20, 30}; int *p = arr; p++; printf("%d\n", *p); return 0; }
Remember that incrementing a pointer moves it to the next element in the array.
Initially, p points to arr[0] which is 10. After p++, it points to arr[1] which is 20. So, *p prints 20.
What happens when this code runs?
#include <stdio.h> int main() { int *p = NULL; printf("%d\n", *p); return 0; }
Think about what happens when you try to access memory through a NULL pointer.
Dereferencing a NULL pointer causes a runtime error (segmentation fault) because it points to no valid memory.
What is the error in this code?
#include <stdio.h> int main() { int *p; *p = 5; printf("%d\n", *p); return 0; }
Think about what p points to before assignment.
The pointer p is declared but not initialized to point to valid memory. Writing to *p causes undefined behavior.
Which option contains the correct pointer declaration?
Remember how to declare a pointer to an int in C.
int *p; declares p as a pointer to an int. Option A uses C++ reference syntax, C does not support it. Option A is invalid syntax. Option A declares an array of pointers, not a single pointer.
What is the output of this program?
#include <stdio.h> #include <stdlib.h> int main() { int *p = malloc(sizeof(int)); *p = 42; free(p); printf("%d\n", *p); return 0; }
Consider what happens when you access memory after it has been freed.
After free(p), the memory is released. Accessing *p is undefined behavior and usually causes a runtime error (use after free).