如何将整个数组指针作为const传递,以使值无法更改?我将数组传递给这样的函数:
double myArr[] { 1, 2, 3, 4, 5 };
double* pArr = myArr;
double myVal = MyFunc(pArr, 5);
Run Code Online (Sandbox Code Playgroud)
MyFunc的标题现在是:
MyFunc(double* pArr, int length)
Run Code Online (Sandbox Code Playgroud)
我想确保该函数根本无法修改数组中的值.
我该怎么做呢?
将您的功能签名更改为:
MyFunc(double const* pArr, int length);
Run Code Online (Sandbox Code Playgroud)
请注意,这相当于:
MyFunc(const double* pArr, int length)
Run Code Online (Sandbox Code Playgroud)
你喜欢哪一个是纯粹的味道(我更喜欢第一个,因为我发现它更具可读性 - 它pArr是const中的项目,而不是指针本身).
| 归档时间: |
|
| 查看次数: |
125 次 |
| 最近记录: |