Day#73 'C' Coding Challenge

Day#73 'C' Coding Challenge

What is the output of the below program?

#include <stdio.h> int arr_1[5] = {1,2,3}; int arr_2[3] = {1,2,3}; void main() { int *ptr_1 = (&arr_1+1); printf("%d\n %d\n", *(arr_1+1), *(ptr_1-1)); int *ptr_2 = (&arr_2+1); printf("%d\n %d\n", *(arr_2+1), *(ptr_2-1)); }

--------------------------------------------------------------

In the above program two integer arrays arr_1 and arr_2 are declared.

arr_1 is partially initialized
arr_2 is completely initialized

Consider the case of ptr_1,

pointer ptr_1 is assigned (&arr_1+1) which means it shall be assigned arraysize+1, if each integer is considered, 4 bytes and array address starts at X, then ptr_1 could be X+4*5 = X+20.

Value at arr_1[X] = 1
Value at arr_1[X+4] = 2
Value at arr_1[X+8] = 3
Value at arr_1[X+12] = 0
Value at arr_1[X+16] = 0

Values at arr_1[X+12] and arr_1[X+16] are zero as they are not initialized in the array.

In the print function, *(arr_1+1) is printed first which meant, value that is incremented by 1 from the base value of array. which is arr_1[1] which is 2.
Also, in the print function, *(ptr_1-1) is printed which meant ptr_1 value decremented by 1 which as considered above shall be X+16 which meant it prints 0.

So, for the first printf output is 2,0

Consider the case of ptr_2,

pointer ptr_2 is assigned (&arr_2+1) which means it shall be assigned arraysize+1, if each integer is considered, 4 bytes and array address starts at X, then ptr_1 could be be X+4*3 = X+12.

Value at arr_1[X] = 1
Value at arr_1[X+4] = 2
Value at arr_1[X+8] = 3

In the print function, *(arr_1+1) is printed first which meant, value that is incremented by 1 from the base value of array. which is arr_1[1] which is 2.
Also, in the print function, *(ptr_1-1) is printed which meant ptr_1 value decremented by 1 which as considered above shall be X+8 which meant it prints 3.

So, for the first printf output is 2,3

Post a Comment

0 Comments