Govt Exams
int a = 10;
int *p = &a;
int *q = p;
q = NULL;
printf("%d", *p);
q = NULL only changes q, not p. p still points to a, so *p prints 10.
int *p = NULL;
int *q = malloc(sizeof(int));
free(q);
free(q);
What is the issue here?
Freeing the same pointer twice causes double free error and undefined behavior. Should set q=NULL after first free.
char *str = "Hello";
str[0] = 'J';
String literals are stored in read-only memory. Attempting to modify causes undefined behavior or segmentation fault.
int arr[] = {10, 20, 30};
int *p = arr;
printf("%d %d", *(p+1), arr[1]);
p+1 points to second element (20). arr[1] is also 20. Both print the same value.
int *ptr;
On a 64-bit system, all pointers are 8 bytes regardless of the data type they point to.
int (*ptr)(int, int) declares a pointer to a function. int *ptr(int, int) declares a function returning pointer to int.
int x = 5;
int *p = &x;
int **q = &p;
printf("%d", **q);
q is a pointer to pointer p. **q dereferences p twice, giving the value of x which is 5.
int * const p is a constant pointer - the pointer address cannot be changed, but the value it points to can be modified.
Valid pointer arithmetic includes addition/subtraction with integers and subtraction between pointers. Multiplication, division, and pointer addition are invalid.
void func(int *arr) { arr[0] = 100; }
int main() {
int a[5] = {1,2,3,4,5};
func(a);
printf("%d", a[0]);
}
Arrays are passed by reference (as pointers). Changes made in func() affect the original array. a[0] becomes 100.