porter i know the code is playing with data segment. i didnt write this code. i just saw it on a "Test ur C skill book" and dint quite understand how the output was mno.
Can you please explain/justify the output???
Yes there is, "p" was assigned point to "def" which is in the data segment, "abc" is also in the data segment, and given the location in the code is likely to immediately follow it in the data segment.
However there is no guarantee on the distance between abc and def, as this may change on compiler, alignment and pointer sizes.
I agree with porter completely, i don't understand why people think that they are testing C skills by asking this question, and other big mistake is stating that this is the exact answer.
as far as the code is concerned
to understand the consequence of the statement p = p + 40,a person need to know that p would be pointing to a memory location 40 bytes ahead
but using this knowledge, no body can predict the output.How can somebody state the output is "mno"
if he/she state's that while using compiler X on operating system Y on Z bit machine we may get the output "mno" is acceptable.
There are some basic things that are wrong with the above code. That's why the output doesn't make sense. You can't equate p to def since p is a pointer to char while def is a pointer to pointer to char. In fact the proper declaration for p and the code should be...
char **p = def;
p=p+40;
printf("%s\n",*p);
The problem occurs probably because def is being cast to a unilevel pointer as in (char *)def and hence outputs garbage.
actully what puzzled me (and why i posted this question) is that the output is consistent in several platforms i ran the code. again this code i got from a book which explains in some vague way why the outout should always be mno