sum += * ( * (arr+i)+(i++));
How does this line run in Q7 ?
Can't understand a line of code in pointers MCQ
@S19WDPP0014 Observe that the unary operator ++ in the program is a post increment operator. Thus
the value of i gets incremented only after the execution of the statement.
Since arr is a 2-D array, arr represents a pointer to an array of pointers, where each
pointer in the array in turn points to a 1-D array(i^th pointer points to the starting location
of i^th row in the array). So, *(arr+i) represents the starting address of i^th row. This
implies *(arr+i)+i represents the address of i^th element in the i^th row, which is
basically a diagonal element.
Let’s dry run the code on an array
arr = [ 1 2 3 ]
[ 4 5 6 ]
[ 7 8 9 ]
At first iteration,
i = 0, sum = 0
sum = sum + *( *(arr+i) + i++ ) ;
sum = sum + *( *(arr+0) + 0 ) ; // i is 1 now because of i++ ;
sum = sum + *((arr[0]) + 0 ) ;
sum = sum + (arr[0][0] ) ;
sum = 0 + 1 ;
sum = 1 ;
At second iteration,
i = 1, sum = 1
sum = sum + *( *(arr+i) + i++ ) ;
sum = sum + *( *(arr+1) + 1 ) ; // i is 2 now because of i++ ;
sum = sum + *((arr[1]) + 1 ) ;
sum = sum + (arr[1][1] ) ;
sum = 1 + 5 ;
sum = 6 ;
At third iteration,
i = 2, sum = 6
sum = sum + *( *(arr+i) + i++ ) ;
sum = sum + *( *(arr+2) + 2 ) ; // i is 3 now because of i++ ;
sum = sum + *((arr[2]) + 2 ) ;
sum = sum + arr[2][2] ;
sum = 6 + 9 ;
sum = 15 ;
every time sum += arr[i][i] is happening and arr[i][i] is the diagonal element. Hence c option is the correct one.
Hope this helps