What is the output of the following program? main() {

What is the output of the following program?

main()
{
	char *s[] = {"ice","green","cone","please"};
	char **ptr[] = {s+3,s+2,s+1,s};
	char ***p = ptr;
	printf("%s ",**++p);
	printf("%s ",*--*++p+3);
	printf("%s ",*p[-2]+3);
	printf("%s",p[-1][-1]+1);
}

 

Answer

s is an array of character pointers, where each pointer points to a character array or string. s[0] points to "ice", s[1] points to "green", s[2] points to "cone", and s[3] points to "please". ptr is an array of character double pointers, where ptr[0] holds to s+3 or points to s[3], ptr[1] points to s[2], ptr[2] points to s[1], and ptr[3] points to s[0]. Next, p is a character triple pointer which points to the base address of the ptr array. So, ++p points to ptr[1], value of ptr[1] is s+2, and value of s[2] is "cone". Therefore, first printf statement prints "cone". Next, as we have already incremented p, p now points to ptr[1]. So, ++p points to ptr[2], value of ptr[2] is s+1, --(s+1) is s, value of s[0] is "ice", and adding 3 with the base location of "ice" gives us nothing, as then it will point to the null character which terminates the string "ice". So, the second printf statement prints nothing. However, after execution of the second printf, p now points to ptr[2]. So, p[-2] or p-2 points to ptr[0], value of ptr[0] is s+3, s[3] points to the string "please", so s[3]+3 points to "ase". Output of the third printf statement is "ase". Next, p still points to ptr[2], so p[-1][-1] = *(*(p-1)-1) = *(ptr[1]-1) = *(s+2-1) = *(s+1) = s[1], s[1] points to "green", so s[1]+1 gives us "reen". Therefore, output of the program is "cone <no output> ase reen".

0Comment