in Programming edited by
210 views
3 votes
3 votes

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
in Programming edited by
210 views

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. 

0
0

2 Answers

4 votes
4 votes

Let Assume Starting Address is 1000

then adress of arr[0] is 1000=ptr1 and adress of arr[5] =1000+(5*4)=1020=ptr2

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.

 

3 votes
3 votes

Answer: 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.

Answer:

Related questions