无法理解指向固定大小数组的指针
Can't understand a pointer to a fixed size array
我是c++的新手,无法弄清楚指针指向固定大小的数组是如何工作的。
我正在读的那本书说:
short tell[10];
short (*pas)[20] = &tell; //pas points to array of 20 shorts
...Thus, the type of pas is short(*)[20]. Also note that because pas is set to
&tell, *pas is equivalent to tell, so (*pas) [0] would be the first element of the array.
我不明白的是,"如果pas,被设置为&tell, *pas相当于tell。因此,(*pas)[0]是数组的第一个元素。"
我不明白if pas如何被设置为&tell,这是一个20字节内存块的地址,而*pas相当于tell。这意味着(*pas)[0]将是数组的第一个元素。
这是我第一次看到这种指针,所以我真的不明白它是如何工作的。
如果这是一个愚蠢的问题,我道歉。谢谢。
数组是c++中的一种对象类型,因此可以使用指向数组的指针或指向数组的引用。在许多上下文中,数组的名称将衰变为指向其第一个元素的指针,但它是而不是只是指向其第一个元素的指针。例如,给定int a[10]; int* i;
,则sizeof(a)
是sizeof(int) * 10
,并且几乎可以肯定不等于sizeof(i)
。
声明指向数组的指针的语法是你们书中展示的难看的语法:
short (*pas)[20]; // declare pas as a pointer to an array of 20 shorts
// pas is a single pointer
与
完全不同 short *foo[20]; // declare foo as an array of 20 pointers to short
// foo is an array containing 20 pointers
你可以把数组的地址赋值给指向数组的指针,就像你可以把int
变量的地址存储在指向int
的指针中:
short stuff[20];
pas = &stuff; // pas now points to the array stuff
你可以写一个通过引用接受数组的函数:
void f(short (&arr)[20]) { } // f takes an array of 20 shorts by reference
short p[20];
short *i = p; // p decays to a pointer to its first element in this context,
// and the resulting pointer is used to initialize i
f(p); // ok, pass the array by reference
f(i); // compile error
现在,示例中的代码是
short tell[10];
short (*pas)[20] = &tell; //pas points to array of 20 shorts
不能编译,因为&tell
的类型是"指向10个short
s的数组的指针",不能赋值给类型为"指向20个short
s的数组的指针"的变量。
假设我们修复了以下代码:
short tell[20];
short (*pas)[20] = &tell; // now compiles! yay!
那么pas
是一个指向20个short
的数组的指针,它指向数组tell
。解引用一个"指向T
的指针"会得到指针指向的T
,所以用*pas
解引用pas
会得到pas
指向的20个short
的数组。然后可以像其他数组一样对该数组使用下标操作符,记住[]
比*
具有更高的优先级,因此需要使用括号:
short c = (*pas)[0]; // initializes c with the first element of the array pas points to
// since pas points to tell, this initializes c with tell[0].
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 声明后,gcc 的动态大小数组是否与标准数组有效相同?
- 将 int 数组转换为带有小数C++的双精度数组
- 如何将大括号初始值设定项用于动态大小数组和新数组?
- 对未知大小数组的引用的列表初始化:它是否应该推断数组大小?
- 返回指向固定大小数组C++的数组的指针
- 如何将小数数组转换为二进制数数组
- 对指向固定大小数组的指针数组的内存分配的解释
- 在 C++ 中创建固定大小的 int 数组的动态大小数组