210 views

Assume that an int variable takes $4$ bytes and a char variable takes $1$ byte. What is the output of the code below?

int main()
{
int arr[]={10,20,30,40,50,60};
int *ptr1=arr;
int *ptr2=arr+5;
printf("Number of elements between two pointer are: %d.",
(ptr2 - ptr1));
printf("Number of elements between two pointer are: %d.",
(char*)ptr2 - (char*)ptr1);
}

1. Number of elements between two pointer are: $5$. Number of bytes between two pointers are: $20$
2. Number of elements between two pointer are: $20.$ Number of bytes between two pointers are: $20$
3. Number of elements between two pointer are: $5.$ Number of bytes between two pointers are: $5$
4. Compile time error

### 1 comment

Very easy question :

prt1 – ptr2 = 20B

Now, if the pointer is of type int we take the difference in terms of 4B each so, 20/4 = 5

& if it is of type char then we take pairs of 1B each : 20/1 = 20

So, option B is right.

Let Assume Starting Address is 1000

now, ptr2-ptr1= (1020-1000)/size of(*ptr1)=5

(char*)ptr2 – (char*)ptr1=(1020-1000)/size of(*ptr1)=20[such that here p1 and p2 both is typecasted).

So The answer is option A.

Question basically asks the number of objects/cells/elements of “type” between two pointers.

ptr1 and ptr2 are pointer of type int. ptr1 = arr + 0, and ptr2 = arr + 5. This one is straight-forward 5.

Now the char typecasted pointers have how many elements of type char? It has 5 ints and sizeof one int is 4 * size of one char, so total 20 char elements.