"address of array"的实际用例是什么?
What's a practical use-case for "address of array"?
(免责声明:C++中的指针是一个非常流行的话题,所以我不得不相信在我之前有人已经提出了这一点。然而,我找不到其他参考。请纠正我的错误,如果我错了,请随时关闭此线程。)
我遇到过很多例子,它们区分了指向数组第一个元素的指针和指向数组本身的指针。以下是一个程序及其输出:
//pointers to arrays
#include <iostream>
using namespace std;
int main() {
int arr[10] = {};
int *p_start = arr;
int (*p_whole)[10] = &arr;
cout << "p_start is " << p_start <<endl;
cout << "P_whole is " << p_whole <<endl;
cout << "Adding 1 to both . . . " <<endl;
p_start += 1;
p_whole += 1;
cout << "p_start is " << p_start <<endl;
cout << "P_whole is " << p_whole <<endl;
return 0;
}
输出:
p_start is 0x7ffc5b5c5470
P_whole is 0x7ffc5b5c5470
Adding 1 to both . . .
p_start is 0x7ffc5b5c5474
P_whole is 0x7ffc5b5c5498
因此,正如预期的那样,两者加1会得到不同的结果。但我不知道p_whole
这样的东西有什么实际用途。一旦我有了整个数组块的地址,也可以使用arr
获得,我该如何处理这样的指针?
对于单个数组,我认为它没有多大意义。它变得有用的地方是多维数组,即数组的数组。指向其中一个子数组的指针就是指向该行的指针,递增它将获得指向下一行的指针。相反,指向内部数组第一个元素的指针是指向单个元素的指针,递增它将获得下一个元素。
int (*)[10]
是比int*
"更强"的类型,因为它保持了数组的大小,因此,您可以将其传递给函数,而无需传递额外的大小参数:
void display(const int(*a)[10]) // const int (&a)[10] seems better here
{
for (int e : *a) {
std::cout << " " << e;
}
}
与
void display(const int* a, std::size_t size) // or const int* end/last
{
for (std::size_t i = 0; i != size; ++i) {
std::cout << " " << a[i];
}
}
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- C++避免重复声明的语法是什么
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- C++从另一个类访问公共静态向量的正确方法是什么
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- C++中名称篡改的目的是什么
- 在 c++ 中拥有一组结构的正确方法是什么?
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 是什么阻止DOMTimerCoordinator::NextID进入无休止的循环
- 派生类销毁的最佳实践是什么
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- 通过JNI传递数据数组的最快方法是什么
- "using namespace std;"在C++的作用是什么?
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- 文件系统:复制功能的速度秘诀是什么
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 使用QQuickFramebufferObject时同步数据的最佳方式是什么
- "Misaligned address error"是什么意思?
- "address of array"的实际用例是什么?