Confusion Array Syntax

Array names are known to decay to pointer such as a[i]

equivalent *(a+i)

. I came across a question that asked me a question:

int main(void)
{
   printf("%c", "abcdefgh"[4]);
   return 0;
}

      

The answer they say e

and the reason they give is that it is a[4]

converted to *(a+4)

, where a

is the base address of the array a

in similar lines, we can find the output of the above question.

But how I don't understand how to a[i]

fade in *(a+i)

, because the compiler treats it that way, but in the code snippet above, how and why would we relate to "abcdef"[4]

this?

+3


source to share


3 answers


You will be surprised if I say that you can even write as follows :)

printf( "%c\n", 4["abcdefgh"] );

      

String literals in C are of character array types. Thus, the string literal "abcdefgh" is of type char[9]

. It also includes a trailing zero.

In expression arrays, as you correctly mentioned, the expansion of pointers to their first elements. Therefore, the string literal decays to a type pointer char *

that points to the first character of the literal that is in'a'

According to C standard (6.5.2.1 array substring)

2 A postfix expression followed by an expression in square brackets []

is an indexed element designation of an array object. the definition of an index operator []

is that E1[E2]

identical (*((E1)+(E2)))

. Because of the conversion rules that apply to binary +

, if E1

is an array object (equivalent to a pointer to the original element of the array object), and E2

is an integer, E1[E2]

denotes the E2

th element E1

(from zero).

So this expression (*((E1)+(E2)))

is independent of whether the initial entry was E1[E2]

orE2[E1]



Going back to the ship code of your code, you have this in this expression

4["abcdefgh"]

      

the string literal is converted to a pointer to its first character. You can think of it as

char *p = "abcdefgh";

      

and you get

4[p]

is equivalent *( 4 + p )

and results in an l character value'e'

+4


source


"abcdefgh"[4]

is equivalent *("abcdefgh" + 4)

. When used in an expression (except when it is the operand of the unary operator &

and sizeof

), "abcdefgh"

represents the base address of the string.

In general, remember that you can use a string literal wherever a pointer is allowed char *

. In the fragment

char *ptr;
p = "abcdefgh";  

      



assignment does not copy characters into p

, but instead p

specifies the first character of the string . C allows indexing pointers, so we can index string literals:

char ch;  
ch = "abcdefgh"[4];  

      

+3


source


"abcdefgh"

- array. It is an array of characters that are similar (but not identical) as if you 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 index operator []

.

0


source







All Articles