Download your favorite Linux distribution at LQ ISO.
Go Back > Forums > Non-*NIX Forums > Programming
User Name
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.


  Search this Thread
Old 05-07-2005, 05:53 AM   #1
Registered: Nov 2003
Location: Bloomington, IL, USA
Distribution: Fedora Core 3
Posts: 126

Rep: Reputation: 15
Question Interesting C Question

Take a look at the following 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 :/
Old 05-07-2005, 06:47 AM   #2
Registered: Mar 2003
Location: Belgium
Distribution: Hardened gentoo
Posts: 323

Rep: Reputation: 30
Re: Interesting C Question

Yes this is quite cool...

In C,
is equivalent to
*(x + i)
, and because of the commutativity (is this the right word in English???) of the addition this is also equivalent to
*(i + x)
which in turn can also be written as

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.

Old 05-07-2005, 11:24 AM   #3
Senior Member
Registered: Nov 2000
Location: Seattle, WA USA
Distribution: Ubuntu @ Home, RHEL @ Work
Posts: 3,892
Blog Entries: 1

Rep: Reputation: 67
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.


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Interesting (My)SQL question rjlee Programming 9 03-07-2005 09:23 AM
Interesting Java question deveraux83 Programming 6 07-08-2004 02:06 PM
One interesting question palanisaravanan Linux - Networking 2 04-21-2004 10:39 AM
An Interesting question about a fresh install gamehack Debian 5 01-27-2004 03:04 PM
Interesting Network/Internet question ChaosX2 Linux - Networking 9 10-03-2001 11:51 AM > Forums > Non-*NIX Forums > Programming

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

Main Menu
Write for LQ is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration