数组参数可以声明为常量吗?

abe*_*nky 2 c arrays constants

如果我使用数组表示法声明函数参数(例如:)int a[],是否有办法使该指针恒定,以便它不能被分配给?

我指的是数组的基数(例如名称),而不是数组中的数据,它仍然可以是非常量。

请参阅下面代码中的注释。

void foo(int *const array) // Array is declared as a Constant Pointer
{
    static int temp[] = { 1, 2, 3 };
    array = temp; // This assignment does not Compile, because array is a Constant Pointer, and cannot be assigned.
                  // This is the behavior I want: a Compile Error, to prevent errant assignments.
}

// Array is declared with array[] notation.
// It will decay to a non-const pointer.
// I want it to decay to a const-pointer.
void bar(int array[])
{
    static int temp[] = { 1, 2, 3 };
    array = temp;
    // This assignment compiles as valid code, because array has decayed into a non-const pointer.
    // Is there a way to declare parameter array to be a Constant Pointer?
}
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种方法来防止函数bar编译,同时仍然使用[]参数列表中的符号。

dbu*_*ush 5

const您可以在括号内添加限定符。这会将其应用于参数本身。

\n
void bar(int array[const]) \n
Run Code Online (Sandbox Code Playgroud)\n

这与您的第一个声明完全相同:

\n
void foo(int *const array)\n
Run Code Online (Sandbox Code Playgroud)\n

正如C 标准第 6.7.6.3p7 节中有关函数声明符的规定:

\n
\n

将参数声明为 \xe2\x80\x98\xe2\x80\x98 类型为 \xe2\x80\x99\xe2\x80\x99 的数组应调整为\n\xe2\x80\x98\xe2\x80\x98qualified指向类型\xe2\x80\x99\xe2\x80\x99 的指针,其中类型限定符(如果有)是在数组类型派生的[和中指定的。]

\n
\n

  • @hyde 是的,我确定。`const int *array` 与 `const int array[]` 相同。 (2认同)