有人可以向我澄清这个数组/指针的想法吗?

Aus*_*ore 5 c++ arrays pointers

为了解释数组只是我们班级的指针(用C++),我的教授向我们展示了这个:

array[5]      // cout'ing this 
*(array + 5)  // would return the same value as this
Run Code Online (Sandbox Code Playgroud)

我完全理解它有点麻烦.这是我的想法:

array是第一个位置的地址,所以如果我们向该地址添加5,我们在内存中移动5个地址.指针运算符从内存位置提取数据.

这是正确的想法吗?这个想法对我来说仍然感到模糊,只是觉得我完全不明白.我想听到别人解释它可能会帮助我更多地理解它.提前致谢!

Pub*_*bby 4

你的想法是正确的。

数组隐式转换为指针。有趣的是,[]适用于指针,而不是数组。

下标运算符[b]定义为*(a + (b))[]被用作语法糖——写起来array[5]比写起来更愉快*(array + 5)

使用指针和整数进行指针算术p + i将地址增加p字节i * sizeof(*p)

char* p; 
p + 5; // address increased by 5

int* p;
p + 5; // address increased by 20 as sizeof(*p) is 4
Run Code Online (Sandbox Code Playgroud)

运算*符执行间接操作。它会告诉你指针所指向的内容。

int x[2];
int* p = &x[0]; // could also be int* p = x;
*p = 5;         // x[0] is now 5
*(p + 1) = 10;  // x[1] is now 10
Run Code Online (Sandbox Code Playgroud)