由于数组衰减为指针,为什么我不能应用const?

Tre*_*key 3 c arrays pointers const parameter-passing

请注意以下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
}
Run Code Online (Sandbox Code Playgroud)

我现在将使用数组语法尝试相同的事情.
如您所知,当作为参数传递时,数组会衰减为指针.
因此,行为应该是相同的.
但是,在使用数组语法时,我无法将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
}
...
Run Code Online (Sandbox Code Playgroud)

有没有办法使用数组语法传递数组,但避免重新分配指针?

chq*_*lie 6

无法使用数组语法指定指针的常量,因为它对实际数组没有意义.

无论如何,函数参数的数组语法有点令人困惑.你真的想要制作函数参数const,使用指针语法.

如果您使用C99引入的扩展数组语法之一来获得最小大小或多个动态维度,我恐怕没有解决方案来指定指针的常量.这不是一个真正的问题恕我直言.