【发布时间】:2016-06-11 21:36:56
【问题描述】:
观察以下将const 应用于指针参数的方式:
void fn1(int * i){
*i = 0; //accepted
i = 0; //accepted
}
void fn2(int const* i){
*i = 0; //compiler error
i = 0; //accepted
}
void fn3(int *const i){
*i = 0; //accepted
i = 0; //compiler error
}
void fn4(int const*const i){
*i = 0; //compiler error
i = 0; //compiler error
}
我现在将尝试使用数组语法做同样的事情。
如您所知,数组在作为参数传递时会衰减为指针。
因此,行为应该是相同的。
但是,在使用数组语法时,我无法将 const 应用于衰减的指针。
void fn1(int i[]){
*i = 0; //accepted
i = 0; //accepted
}
void fn2(int const i[]){
*i = 0; //compiler error
i = 0; //accepted
}
void fn3_attempt1(int i[] const){ //<-- can't apply const this way
*i = 0; //accepted
i = 0; //compiler error
}
void fn3_attempt2(int i const[]){ //<-- can't apply const this way
*i = 0; //accepted
i = 0; //compiler error
}
...
有没有办法使用数组语法传递数组,但避免重新分配指针?
【问题讨论】:
-
限定符必须在要限定的变量之前。 (感谢奥拉夫)
-
@DavidC.Rankin:
const准确地说是一个限定词。 -
int const是不推荐使用的语法和过时的功能。限定符应该在类型之前。目前尚不清楚您的意思。int i[]作为形参转换为int * -
“如你所知,数组衰减为指针” - 我知道得更清楚。如前所述,这是错误的。
-
@Olaf 链接到限定符的折旧类型后?
标签: c arrays pointers parameter-passing constants