考虑以下代码:
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是一个常量指针,为什么我可以把它发送给一个没有接收常量指针的函数呢?
代码编译时不会出现丢弃常量限定符的警告。
发布于 2010-10-01 21:27:26
我的问题是arr是否为常量指针
它不是一个const指针。
下面是如何声明常量指针的方法。
const char constArray[] = { 'H', 'e', 'l', 'l', 'o', '\0' };C标准(C99 6.3.2.1/3)规定:“除非是sizeof运算符或一元&运算符的操作数,或者是用于初始化数组的字符串文字,否则类型为‘’array‘’的表达式将转换为类型为‘’pointer type‘’的表达式,该类型指向数组对象的初始元素,而不是左值。
int b[100]; // b is an array of 100 ints.
int* p; // p is a pointer to an int.
p = b; // Assigns the address of first element of b to p.
p = &b[0]; // Exactly the same assignment as above.
p = b; // Legal -- p is not a constant.
b = p; // ILLEGAL because b is a constant, altho the correct type.来源:http://www.fredosaurus.com/notes-cpp/arrayptr/26arraysaspointers.html
https://stackoverflow.com/questions/3839553
复制相似问题