Computer Science, asked by mounikar462, 1 year ago

Consider an array int num[ ] = {1, 2, 3, 4, 5 ,6 };. p1 & p2 are two pointers of type (int *). If p1 = num and p2 = p1 + 5 then what is the value of (char*)p2 - (char*)p1. Note: 'int' and 'char' takes 4 bytes and 1 byte respectively

Answers

Answered by swamiabhijit93
6

I will explain it step by step :

int arr[] = {10, 20, 30, 40, 50, 60};

This statement creates an array with six elements named arr.

int *ptr1 = arr;

This statement creates a pointer of int type named ptr1 which is pointing to the         address of the zeroth(arr[0]) element of the array arr[].

int *ptr2 = arr + 5;

This statement creates a pointer of int type named ptr2 which is pointing to the pointing to the sixth(arr[5]) element of the array arr[].

printf("Number of elements between two pointer are: %d.",  (ptr2 - ptr1));

Now here the subtraction of the pointer is taking place which is just the difference between the position of the arr[5] and arr[0] which is 5 space so the answer is 5.

printf("Number of bytes between two pointers are: %d",   (char*)ptr2 - (char*) ptr1);

Now here due to the casting of the pointers the pointers are pointing to the respective addresses. So let us assume that the array has the starting address (arr[0]) 65514 then the next element(arr[1]) will be at the address 65518 as the size of one int is 4 bytes and so on. So the address of the arr[5] will be 65534.

So (char*)ptr2 - (char*)  just subtracts the addresses 65534 and 65514 giving the output as 20.

Note : If you use the old TurboC compiler then  second output will be 10 as  it has the size of the int as 2 byes.But the first output will still be 5 as the difference between the position is 5.

Similar questions