Predict the output of following C programs:
Difficulty Level: Rookie
ptr2 - ptr1 = 5 (char*)ptr2 - (char*) ptr1 = 20
In C, array name gives address of the first element in the array. So when we do ptr1 = arr, ptr1 starts pointing to address of first element of arr. Since array elements are accessed using pointer arithmetic, arr + 5 is a valid expression and gives the address of 6th element. Predicting value ptr2 – ptr1 is easy, it gives 5 as there are 5 inetegers between these two addresses. When we do (char *)ptr2, ptr2 is typecasted to char pointer. In expression “(int*)ptr2 – (int*)ptr1”, pointer arithmetic happens considering character poitners. Since size of a character is one byte, we get 5*sizeof(int) (which is 20) as difference of two pointers.
As an excercise, predict the output of following program.
arr = geeks, sizeof(arr) = 17 str = geeks, sizeof(str) = 4
Let us first talk about first output “arr = geeks”. When %s is used to print a string, printf starts from the first character at given address and keeps printing characters until it sees a string termination character, so we get “arr = geeks” as there is a \0 after geeks in arr.
Now let us talk about output “sizeof(arr) = 17”. When a character array is initialized with a double quoted string and array size is not specified, compiler automatically allocates one extra space for string terminator ‘\0′ (See this Gfact), that is why size of arr is 17.
Explanation for printing “str = geeks” is same as printing “arr = geeks”. Talking about value of sizeof(str), str is just a pointer (not array), so we get size of a pointer as output (which can also be equal to 8 in case you are using a 64 bit machine).
Please write comments if you find above answer/explanation incorrect, or you want to share more information about the topic discussed above