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

Both the printfs 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.

Kiril Kirov
  • 37,467
  • 22
  • 115
  • 187
Piyush Bhardwaj
  • 633
  • 6
  • 22

3 Answers3

5

Because those are equivalent expressions. Indexing is equivalent to pointer arithmetic.

int x[10];
int y = x[1];
// same as (and is converted by the compiler to)...
int y = *(x + 1);

Since addition is commutative, it is also the same as...

int y = *(1 + x);

And...

int y = 1[x];

On a side note, you are invoking undefined behavior by using the %s format specifier and passing in a char. %s expects a null terminated string, i.e., a pointer to char terminated by a null character. Heed your warnings.

If you want to print a substring in that array, use:

printf("%s", a + 3);
// or
printf("%s", &a[3]);
Ed S.
  • 122,712
  • 22
  • 185
  • 265
1

You need to use the %c format specifier for a[3] as it is a character, not a string.%s is used for strings, not individual characters.

As for your question why both have same output, well Both are Same!! Both are interpreted as *(a+3).In C you can do it both ways.

And make some corrections to your code:

printf("%s", a[3]);
printf("%s", 3[a]);

would be

printf("%c", a[3]);
printf("%c", 3[a]);

To print the whole string , you can use either :

printf("%s", a);

OR

printf("%s", &a[0]);
Rüppell's Vulture
  • 3,583
  • 7
  • 35
  • 49
1

In C a[i] is converted to *(a+i) internally. i[a] is converted to *(i+a). Array names also act as pointers in c. so (a+i) or (i+a) give an address (using pointer arithmetic) that is dereferenced using *

Suvarna Pattayil
  • 5,136
  • 5
  • 32
  • 59