Govt Exams
int *p = (int*)malloc(5 * sizeof(int));
int *q = p;
p = NULL;
free(q);
q still holds the address even though p is NULL. free(q) properly deallocates memory.
int x = 5;
int *const p = &x;
x = 10;
printf("%d", *p);
const pointer p cannot be changed, but x can be modified. *p prints current value of x which is 10.
int *p, *q;
p = q; // What happens?
p = q copies the address stored in q to p. Now both point to same location.
char str[] = "ABC";
char *p = str;
printf("%c", *(p+2));
p+2 points to str[2] which is 'C'. Note: str[3] is null terminator.
malloc(0) behavior is implementation-defined but typically returns a valid pointer. Freeing it is safe.
arr points to arr[0], p points to arr[2]. arr - p = -2 (p is 2 positions ahead).
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int x = 5, y = 10;
swap(&x, &y);
printf("%d %d", x, y);
swap() exchanges values through pointers. x becomes 10, y becomes 5 after function call.
void* is a generic pointer. It can be cast to any other pointer type. No arithmetic can be done directly.
int arr[2][3] = {{1,2,3}, {4,5,6}};
int *p = (int*)arr;
printf("%d", *(p+4));
Array flattened: 1,2,3,4,5,6. p+4 points to 5th element which is 5.
Pointer multiplication is not allowed. Valid operations are addition, subtraction, increment, decrement, and comparison.