Tuesday, July 14, 2009

Why does this piece C code work?

Why did the following program work?





Please note that i is an integer and s[] is an array.


How i[s] is interpreted?








main()


{


char s[ ]="worst";


int i;


for(i=0;s[ i ];i++)


printf("\n%c",i[s]);


}

Why does this piece C code work?
The trick to this program is to understand why i[s] is the same thing as s[i]. I will try to explain this.


Firstly, its important to understand what x[i] means.





In C, if x is an array, then it just contains a pointer to the first element in the array. We can rewrite x[i] using pointer arithmetic as:





*(x + i) [do you understand why?]





Just to be sure that this form is correct, lets check it for x[0]:





*(x+0) = *x





Now since x is a pointer to the first element in the array, this identity is true. Now let us have a look at your example





s[i] = *(s + i)


but what is i[s]?


i[s] = *(i + s)





Now simplifying that last equation, we know that (i + s) is the same is (s + i) which means that


*(i + s) = *(s + i)


which means that s[i] = s[i].





Hope that helped!
Reply:ya, its possible, i[s] is just another representation of s[i]. it'll print "worst" in the console.
Reply:s is a character array containing 6 characters---w,o,r,s,t and a '\0' (null character) in the end. ASCII value of '\0' is zero.





so if you write


printf("%d",s[5]);


it will print 0 because the ASCII value of '\0' is zero.








The for loop will run until ASCII value of s[i] is non-zero.


___________________


I suggest you join this forum:


http://cboard.cprogramming.com/

song downloads

No comments:

Post a Comment