C Programming - Strings - Discussion

Discussion Forum : Strings - Find Output of Program (Q.No. 18)
18.
What will be the output of the program ?
#include<stdio.h>

int main()
{
    static char mess[6][30] = {"Don't walk in front of me...", 
                               "I may not follow;", 
                               "Don't walk behind me...", 
                               "Just walk beside me...", 
                               "And be my friend." };

    printf("%c, %c\n", *(mess[2]+9), *(*(mess+2)+9));
    return 0;
}
t, t
k, k
n, k
m, f
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
21 comments Page 2 of 3.

Smash said:   9 years ago
Thank you very much @Abhimanyu.

Naga Venkatesh Gavini said:   9 years ago
2nd row=>d o n ' t _ w a l k

Where k is the 9th element in the 2nd row. So, its get's printed.

Raju Singh Kumai said:   1 decade ago
*(mess[2]+9) can be written as mess[2][9] which implies 3 line 10 char.(in c we start from 0) which is 'k',

*(*(mess+2)+9))=*(mess[2]+9) = mess[2][9] = k.

So the output will be k, k.
(2)

Inside C said:   1 decade ago
*(mess[2]+9)
=>mess[2][9]

*(*(mess+2)+9))
=>*(mess[2]+9)
=>mess[2][9]

So simple logic is * and + combines to form [].

Sss said:   1 decade ago
Thanks Abhimanyu.

Sonu said:   1 decade ago
Thanks Abhimanyu.

Raghu said:   1 decade ago
*(mess[2]+9)=mess[2] is incremented in the position for 9 times and k is printed.
*(*(mess+2)+9)= *(mess+2)=*mess[2]

Tim said:   1 decade ago
Yes, the problem is about PRECEDENCE of the * operator vs pointer arithmetic.

The expression * (mess+2) +9 is evaluated as mess+2 first (because it is within parentheses) which evaluates to the THIRD ROW of the matrix "mess". This is a char* value, so the next operation is to add +9 to that char* -- which gives us a pointer to the character 'k'. If you change the +9 to +j and do a printf for one character at a time, j = 0 to 9, then you will see you are printing the first 10 characters of the second row of the variable 'mess'.

Abhimanyu Verma said:   1 decade ago
As we can see this is a matrix having 6+1 row and 30+1 column.

So now *(mess[2]+9)means that third row of matrix that is "Don't walk behind me...", and its (9+1)th character that is K

and *(*(mess+2)+9)) this one have the same meaning as *(mess[2]+9)bcoz a[i]=*(a+i). So has same value K.....

Swetha said:   1 decade ago
Please give us more details of solving this type of questions


Post your comments here:

Your comments will be displayed after verification.