LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Interesting C Question (https://www.linuxquestions.org/questions/programming-9/interesting-c-question-320964/)

ar1 05-07-2005 04:53 AM

Interesting C Question
 
Take a look at the following code:

Code:

char a[10] = "abcdefghi";
printf("%s", a[3]);
printf("%s", 3[a]);

Both the printf's give the same output. Why??

It must be something to do with the way the string is represented in the memory by the C compiler, but what is it?

I would have thought that the offset is multiplied by the size of char, in which case they should give different outputs :/

nukkel 05-07-2005 05:47 AM

Re: Interesting C Question
 
Yes this is quite cool...

In C,
Code:

x[\i]
is equivalent to
Code:

*(x + i)
, and because of the commutativity (is this the right word in English???) of the addition this is also equivalent to
Code:

*(i + x)
which in turn can also be written as
Code:

i[x]
...

Quote:

Originally posted by ar1
I would have thought that the offset is multiplied by the size of char, in which case they should give different outputs :/ [/B]
sizeof (char) = 1, so that makes no difference here.

greets,
nukkel

jtshaw 05-07-2005 10:24 AM

The size of the type actually shouldn't matter in this case. Pointers in C are always the same size, regardless of the datatype they are pointing too.


All times are GMT -5. The time now is 09:39 PM.