#include<stdio.h> 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 bytes between two pointers are: %d", (char*)ptr2 - (char*) ptr1); return 0; } |
Assume that an int variable takes 4 bytes and a char variable takes 1 byte
(A) Number of elements between two pointer are: 5.
Number of bytes between two pointers are: 20
(B) Number of elements between two pointer are: 20.
Number of bytes between two pointers are: 20
(C) Number of elements between two pointer are: 5.
Number of bytes between two pointers are: 5
(D) Compiler Error
(E) Runtime Error
Answer: (A)
Explanation: Array name gives the address of first element in array. So when we do ‘*ptr1 = arr;’, ptr1 starts holding the address of element 10. ‘arr + 5’ gives the address of 6th element as arithmetic is done using pointers. So ‘ptr2-ptr1’ gives 5. When we do ‘(char *)ptr2’, ptr2 is type-casted to char pointer and size of character is one byte, pointer arithmetic happens considering character pointers. So we get 5*sizeof(int)/sizeof(char) as a difference of two pointers.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- C | Pointer Basics | Question 2
- C | Pointer Basics | Question 7
- C | Pointer Basics | Question 4
- C | Pointer Basics | Question 3
- C | Pointer Basics | Question 1
- C | Pointer Basics | Question 11
- C | Pointer Basics | Question 12
- C | Pointer Basics | Question 15
- C | Pointer Basics | Question 17
- C | Pointer Basics | Question 16
- C | Pointer Basics | Question 17
- C | Pointer Basics | Question 17
- C | Pointer Basics | Question 14
- C | Pointer Basics | Question 8
- C | Pointer Basics | Question 10
- C | Pointer Basics | Question 13
- Double Pointer (Pointer to Pointer) in C
- C++ | this pointer | Question 5
- C++ | this pointer | Question 4
- C++ | this pointer | Question 1

