考虑以下代码:
void Increment(int *arr) {
arr++;
}
int main() {
int arr[] = {1,2,3,4,5};
// arr++ // illegal because its a const pointer
Increment(arr); // legal
}
我的问题是,如果 arr
是一个 const 指针,我怎么能将它发送给一个不接收 const 指针的函数呢?
代码编译时没有丢弃 const 限定符的警告。
最佳答案
My question is if arr is a const pointer, how come i can send it to a function that doesn't receive a const pointer?
arr
(在 main()
内)不是一个 const 指针,它是一个数组。当传递给函数时,数组类型会退化为指针类型。
Increment
中的 arr
(参数)保存参数 arr
的地址拷贝(通过值从 main( )
).
// arr++ // ileagal because its a const pointer
这是非法的,因为arr
是一个不可修改的lvalue
。
关于c++ - 数组作为 const 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3839553/