为什么在 C++ 中,我不需要取消引用数组的指针来访问数组中的项

Kai*_*Luo 4 c++ arrays pointers

我目前正在学习指针。当我创建一个指向 int 类型数组的指针时,我发现我可以直接索引指针而不延迟指针,并且编译器仍然在我的数组中输出精确的项目。我不明白为什么这行得通,为什么我们不需要首先尊重指针。

没有取消引用的代码

int arraySize = 5;
int* theArray = new int[arraySize];

for(int i = 0; i < 5; i++)
{
    theArray[i] = i;
}

for (int i = 0; I < 5; i++)
{
    std::cout << theArray[i] << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

这给了我输出

不解引用的输出

但是,当我这样写时:

for (int i = 0; i < 5; i++)
{
    (*theArray)[i] = i;
}
Run Code Online (Sandbox Code Playgroud)

我的编译器说:错误:表达式必须具有指向对象的类型。(我使用的是 Visual Studio 2013。)

任何帮助,将不胜感激。

Sam*_*hik 6

没有取消引用的代码

[ code ]
Run Code Online (Sandbox Code Playgroud)

那是不正确的。您肯定是在取消引用您的指针:

 theArray[i] = i;
Run Code Online (Sandbox Code Playgroud)

那是一个指针取消引用。该[]运营商取消引用指针。这相当于:

 *(theArray+i) = i;
Run Code Online (Sandbox Code Playgroud)

如您所知,向指针添加或减去值会增加或减少指针,产生一个新的指针值,然后指针被取消引用。

还:

 *p = q;
Run Code Online (Sandbox Code Playgroud)

相当于

 p[0] = q;
Run Code Online (Sandbox Code Playgroud)

[]操作者仅仅是将偏移到指针,并且解引用与所得到的指针的简写*运算符。最终结果完全相同。