Please Explain me the output

#include<stdio.h>

char *def[5]={"pqrs","rstu","tuvw","vwxyz","xyzab"};
char abc[5][5]={"abc","def","ghi","jkl","mno"};

void main()
{
char *p=(char *)def;
p=p+40;
printf("%s\n",p);
}

the output of the abve code snippet is mno...
HOW??? beats me.. please help

Your code is leaping around in the data segment. No surprises.

The give away is you have to cast from "def" showing you are trying to cheat the compiler.

As for the "40", it shows you have no concern for any array bounds.

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???

I thought I just did.

you didnt porter. you just commented how bad the code is... Or maybe am too dumb to understand how you explained the output.

let me ask my question straight.

when i increment p by forty how is it poingting to another last element of char array abc. there is no relation between p and abc.

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" :confused:

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.

I am sorry man, please don't take it as a offense

Rakesh UV

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

What compiler and on what platform is it giving this output? I am unable to duplicate your results.

am using SUNOS 5.9 with cc compiler