如果我使用陣串列示法(例如:)宣告函式引數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編譯,同時仍然使用[]引數串列中的符號。
uj5u.com熱心網友回復:
您可以const在括號內添加限定符。這會將其應用于引數本身。
void bar(int array[const])
這完全等同于您的第一個宣告:
void foo(int *const array)
正如C 標準的第 6.7.6.3p7 節中關于函式宣告符的說明:
將引數宣告為“型別陣列”應調整為“型別限定指標”,其中型別限定符(如果有)是陣列型別派生的
[和中指定的那些。]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/530478.html
標籤:数组C常数
下一篇:通過bool函式檢查中獎
