How does this code works?

1
2
3
4
5
main()
{
char thought[20][30]={"Don't walk in front of me..", "I may not follow"};
printf("%c%c", *(thought[0]+9), *(*(thought+0)+5);
}


I couldn't understand line2
also whats stored in thought[3][], thought[4][]....?

Im using Turbo C
Last edited on
What's to understand in line 2? Its the opening bracket for the main...

thought[3][], thought[4][] onwards is garbage...
thought[x] is an array of chars (which can be implicitly cast to a pointer to a char)
thought is an array of char arrays (which can be implicitly cast to a pointer to an array of chars)

In C and C++ (barring unusual overloads), a[b] is the same as *(a + b). This can be seen any number of ways:

1
2
3
4
int foo[5] = {1,2,3,4,5};

cout << foo[2];  // outputs '2'
cout << *(foo+2); // also outputs '2'... it's the same thing as the above line 


With that in mind, *(thought[0]+9) is the same as thought[0][9], it's just an ugly and more confusing way to write it. thought[0][9] gives you the 'k' in "walk".

And therefore, *(*(thought+0)+5) is the same as thought[0][5] for the same reason. It gives you the space between "Don't" and "walk".

Therefore (Assuming the other errors in this program were fixed), this program would output k (that is, k followed by a space).

thought[2][x] and onwards would all be null characters (empty strings). If you partially initialize an array of built-in types, the other elements of that array are automatically zero'd.
It's a two-dimensional array with a sequence of characters stored in each block.

Line two is the opening bracket for the main function as Caprico said, and thought[3][] and thought[4][] are the third and fourth parts of the arrays indice(value).
Last edited on
Thanks Disch so much!!!!
Resolved the confusing part
Thanks once again!!!!!!!!!!!
Sorry I meant the second executable line!
@Disch:
1
2
3
4
int foo[5] = {1,2,3,4,5};

cout << foo[2];  // outputs '2'
cout << *(foo+2); // also outputs '2'... it's the same thing as the above line 

That outputs 3, you fool. :p
closed account (zb0S216C)
Here's another way of accessing an array: 3[foo]; :)P

Wazzak
Thanks framework
whoops @ Gaminic. You're right.
Topic archived. No new replies allowed.