如何访问以下字符数组

huangapple go评论47阅读模式
英文:

How is the following character array accessed

问题

以下是您要翻译的代码部分:

#include <iostream>
using namespace std;

int main()
{
    char str[]="ABCD";
    
    for(int i=0;str[i]!='
#include <iostream>
using namespace std;

int main()
{
    char str[]="ABCD";
    
    for(int i=0;str[i]!='\0';i++)
    {
        cout<<str[i]<<" ";
    }
    return 0;
}
'
;i++)
{ cout<<str[i]<<" "; } return 0; }

这段代码的输出是 A B C D,但我不理解我们如何访问数组。

英文:
#include &lt;iostream&gt;
using namespace std;

int main()
{
    char str[]=&quot;ABCD&quot;;
    
    for(int i=0;str[i]!=&#39;
#include &lt;iostream&gt;
using namespace std;
int main()
{
char str[]=&quot;ABCD&quot;;
for(int i=0;str[i]!=&#39;\0&#39;;i++)
{
cout&lt;&lt;i[str]&lt;&lt;&quot; &quot;;
}
return 0;
}
&#39;;i++) { cout&lt;&lt;i[str]&lt;&lt;&quot; &quot;; } return 0; }

The output of the following code is A B C D but i am not able to understand how we are accessing the array

答案1

得分: 0

让我们考虑字符串 str 的地址为 100(非常简化的示例)。

它有5个字符,因此地址分别为 100、101、102、103、104,其中 104 是 '\0'。

当你尝试访问 str[i] 时,它实际上计算地址 str + i,并获取值:*(str + i)。当你尝试以倒置的方式写 i[str] 时,它也计算地址 i + str。因此你得到正确的结果。

注意这里使用了指针算术运算(所以对于每种类型 T,你得到地址指针 + sizeof(T))。

而你的

for(int i=0;str[i]!='
for(int i=0;str[i]!='\0';i++)
{
    cout<<i[str]<<" ";
}
'
;i++)
{ cout<<i[str]<<" "; }

将访问地址 100、101、102、103、104,并打印出正确的值。

英文:

Let's consider str has address 100 (Very simplified example).

It has 5 chars in it, so the addressed are 100, 101, 102, 103, 104, where in the 104 is '\0'

When you try to access str[i], it actually calculates the address str + i, and gets the value: *(str + i). And when you try to write the reversed way i[str], it also calculates the address i + str. So you get correct result.

Note that here is working pointer arithmetic (so for every type T you get the address pointer + sizeof(T))

And your

for(int i=0;str[i]!=&#39;
for(int i=0;str[i]!=&#39;\0&#39;;i++)
{
cout&lt;&lt;i[str]&lt;&lt;&quot; &quot;;
}
&#39;;i++) { cout&lt;&lt;i[str]&lt;&lt;&quot; &quot;; }

Will access addresses 100, 101, 102, 103, 104. And print the right values.

huangapple
  • 本文由 发表于 2023年2月16日 11:28:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75467567.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定