簡體   English   中英

由於數組衰減為指針,為什么我不能應用const?

[英]Since arrays decay to pointers, why can't I apply const?

請注意以下可以將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
}
...

有沒有辦法使用數組語法傳遞數組,但避免重新分配指針?

無法使用數組語法指定指針的常量,因為它對實際數組沒有意義。

無論如何,函數參數的數組語法有點令人困惑。 真的想讓函數參數為const ,使用指針語法。

如果您使用C99引入的擴展數組語法之一來獲得最小大小或多個動態維度,我恐怕沒有解決方案來指定指針的常量。 這不是一個真正的問題恕我直言。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM