Reputation:
It is a known thing that array names decay into pointer such as a[i]
is equivalent to *(a+i)
. I stumbled upon a question asking me predict the output of:
int main(void)
{
printf("%c", "abcdefgh"[4]);
return 0;
}
The answer they say is e
and the reason given by them is as a[4]
gets converted into *(a+4)
where a
is base address of array a
on similar lines we can find the output of above question.
But how I don't understand as with a[i]
decaying into *(a+i)
because compiler treats it that way but in the code snippet above how and why we will treat "abcdef"[4]
this?
Upvotes: 3
Views: 85
Reputation: 106012
"abcdefgh"[4]
is equivalent to *("abcdefgh" + 4)
. When used in an expression (except when it is an operand of unary &
and sizeof
operator) "abcdefgh"
represents the base address of string.
In general, remember that one can use a string literal wherever char *
pointer is allowed. In the snippet
char *ptr;
p = "abcdefgh";
the assignment doesn't copy the characters to p
instead it makes p
points the first character of the string. C allows pointers to be subscripted, so we can subscript string literals:
char ch;
ch = "abcdefgh"[4];
Upvotes: 3
Reputation: 310980
You will wonder even more if I say that you can write even the following way :)
printf( "%c\n", 4["abcdefgh"] );
String literals in C have types of character arrays. Thus string literal "abcdefgh" has type char[9]
. It includes also the terminating zero.
In expressions arrays as you correctly mentioned decay to pointers to their first elements. So the string literal decays to a pointer of type char *
that points to the first character of the literal that is to 'a'
According to the C Standard (6.5.2.1 Array subscripting)
2 A postfix expression followed by an expression in square brackets
[]
is a subscripted designation of an element of an array object. The definition of the subscript operator[]
is thatE1[E2]
is identical to(*((E1)+(E2)))
. Because of the conversion rules that apply to the binary+
operator, ifE1
is an array object (equivalently, a pointer to the initial element of an array object) andE2
is an integer,E1[E2]
designates theE2
th element ofE1
(counting from zero).
Thus this expression (*((E1)+(E2)))
does not depend on whether the initial record was E1[E2]
or E2[E1]
Returning to your code shippet you have that in this expression
4["abcdefgh"]
the string literal is converted to the pointer to its first character. You can imagine this like
char *p = "abcdefgh";
and you will get
4[p]
is equivalent to *( 4 + p )
and results in lvalue of character 'e'
Upvotes: 4
Reputation: 9343
"abcdefgh"
is an array. It is an array of characters, similar (but not identical) to as if you had declared a variable of type char[9]
and static
storage duration:
static char str[9] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 0 };
Hence, you can index it just like any other array, using the []
subscript operator.
Upvotes: 0