Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does an expression like arr[''hi there"] imply?

Tags:

arrays

c

If a=3 and b=5 what does this imply?

printf(&a["Ya!Hello! how is this? %s\n"], &b["junk/super"]);

I know that arr[4] means *(arr+4) so I need to know what does an expression like "hi there" imply?

EDIT - Question in probably clearer terms:

When a string is used as an array subscript what value does it convey ?

Why is output of above Hello! how is this? super ?

like image 705
sun Avatar asked Jul 20 '11 19:07

sun


2 Answers

That implies, the printf becomes equivalent to this:

printf("Hello! how is this? %s\n", "super");

which will print:

Hello! how is this? super

Online demo : http://ideone.com/PVzUP

Explanation:

When we write char s[]="nawaz; and then s[2] means 3rd character in the string s. We can express this by writing "nawaz"[2] which also means 3rd character in the string "nawaz". We can also write 2["nawaz"] which also means 3rd character in the string. In your code, the printf uses the last form, i.e of the form of 2["nawaz"]. Its unusual, though.

So a["Ya!Hello! how is this? %s\n"] means 4th character in the string (as the value of a is 3), and if you add & infront of a then &a["Ya!Hello! how is this? %s\n"] returns the address of the 4th character in the string, that means, in the printf it becomes equivalent to this:

Hello! how is this? %s\n

And I hope you can interpret the rest yourself.

like image 193
Nawaz Avatar answered Oct 24 '22 12:10

Nawaz


If arr[4] means *(arr+4), then 4[arr] means *(4+arr). Since addition between pointers and integers is commutative, these are identical.

The answer could be very different if you are working in C++ with objects that have overloaded operators. In that case, your question is not sufficiently complete.

like image 24
Greg Hewgill Avatar answered Oct 24 '22 12:10

Greg Hewgill