字符串作为数组索引 [英] String as an array index

查看:169
本文介绍了字符串作为数组索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

3["XoePhoenix"]中,数组索引是字符数组类型.我们可以用C语言做到吗?数组索引必须是整数不是真的吗?

In 3["XoePhoenix"], array index is of type array of characters. Can we do this in C? Isn't it true that an array index must be an integer?

3["XeoPhoenix"]是什么意思?

推荐答案

3["XoePhoenix"]"XoePhoenix"[3]相同,因此它将求值为char 'P'.

3["XoePhoenix"] is the same as "XoePhoenix"[3], so it will evaluate to the char 'P'.

C中的数组语法与编写*( x + y )的方式完全不同,其中xy是方括号之前和之内的子表达式.由于加法的可交换性,可以在不更改表达式含义的情况下交换这些子表达式.

The array syntax in C is not more than a different way of writing *( x + y ), where x and y are the sub expressions before and inside the brackets. Due to the commutativity of the addition these sub expressions can be exchanged without changing the meaning of the expression.

因此,3["XeoPhoenix"]被编译为*( 3 + "XeoPhoenix" ),其中字符串衰减为指针,而3添加到该指针,这又导致指向字符串中第4个字符的指针. *取消引用此指针,因此该表达式的值为'P'.

So 3["XeoPhoenix"] is compiled as *( 3 + "XeoPhoenix" ) where the string decays to a pointer and 3 is added to this pointer which in turn results in a pointer to the 4th char in the string. The * dereferences this pointer and so this expression evaluates to 'P'.

"XeoPhoenix"[ 3 ]将被编译为*( "XeoPhoenix" + 3 ),您会看到将导致相同的结果.

"XeoPhoenix"[ 3 ] would be compiled as *( "XeoPhoenix" + 3 ) and you can see that would lead to the same result.

这篇关于字符串作为数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆