[英]How come C standard library function `strchr` returns pointer to non-const, when given `const char *` as first argument?
[英]How to change an argument “const” to “non-const” when calling a function in C
當該函數被其他函數調用時,我遇到了問題。
我的功能是這樣的:
void *table_lookup(const table *t) {
...
//Here I want to call my other function.
table_remove(t);
...
}
void table_remove(table *t) {
...
}
編譯時收到警告。 問題是我無法更改參數的類型。
你不能拋棄const
限定符。 此后任何修改被限定為const
的值的嘗試都會調用Undefined Behavior 。 請參閱C11 標准 - 6.7.3 類型限定符(p6) 。
table_lookup
參數是const
限定的,這是有原因的。 它允許編譯器優化t
的使用。 如果您拋棄const
並嘗試修改t
,則您違反了對編譯器的承諾t
不會被修改。
相反,您應該重構您的代碼,以便remove()
函數在其中調用table_lookup
以獲得指向您希望刪除的節點的指針(大概)。 然后刪除node
。 不要嘗試在table_lookup
中添加remove()
。 創建一個新函數。
在 C 中,您可以直接強制轉換它以刪除“const”屬性。
void *table_lookup(const table *t)
//Here I want to call my other function.
table_remove((table*)t) // remove 'const' by directly casting.
...
return
void table_remove(table *t)
...
您可以拋棄const
限定符: table_remove((table *)t);
但是如果table_remove
嘗試修改table
結構,例如如果它存儲在只讀段中,您可能會遇到問題。
因此,您不應該這樣做。 無論如何,查找函數會修改表是相當出乎意料的。 如果這樣做是有充分理由的,例如構建哈希表或維護緩存,則不應將參數聲明為const
。
是的,這是正確的。 拋棄 const 限定符是個壞主意。 . 我也無法添加新功能。 ((table)*) 給出問題。
你可以試試下面的代碼:
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-qual"
void *table_lookup(const table *t) {
table_remove((table *)t);
}
#pragma GCC diagnostic pop
來自: https ://stackoverflow.com/a/13253997/5093308
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.