gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:01:15 24 4
gpt4 key购买 nike

如果我使用数组表示法声明函数参数(例如: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?
}

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

最佳答案

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

void bar(int array[const]) 

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

void foo(int *const array)

C standard 第 6.7.6.3p7 节所述关于函数声明符:

A declaration of a parameter as ‘‘array of type’’ shall be adjusted to‘‘qualified pointer to type’’, where the type qualifiers (if any) arethose specified within the [ and ] of the array type derivation.

关于arrays - 数组参数可以声明为常量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74364292/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com