[英]Why does the compiler complain about the assignment?
在編譯以下代碼時,編譯器會產生警告:
#include<stdio.h>
int main(void)
{
char * cp;
const char *ccp;
cp = ccp;
}
而且此代碼還可以(沒有警告)。為什么?
#include<stdio.h>
int main(void)
{
char * cp;
const char *ccp;
ccp = cp;
}
編輯:那為什么不行呢?
int foo(const char **p)
{
// blah blah blah ...
}
int main(int argc, char **argv)
{
foo(argv);
}
因為添加constness是“安全”的操作(您將只能對指向的對象進行限制,這沒什么大不了的),而刪除constness則不是(您保證不會通過該指針觸摸指向的對象,現在您可以正在嘗試收回您的諾言)。
至於其他問題,請在C-Faq中進行解釋: http : //c-faq.com/ansi/constmismatch.html 。 簡而言之,允許這種轉換將允許另一種“不安全”的行為:
int give_me_a_string(const char **p)
{
const char *str="asd";
*p=str; // p is a pointer to a const pointer, thus writing
// a in *p is allowed
}
int main()
{
char *p;
give_me_a_string(&ptrs); //< not actually allowed in C
p[5]='a'; // wooops - I'm allowed to edit str, which I promised
// not to touch
}
在第一種情況下,您將獲得一個指向不能修改的數據的指針( const
),並將其分配給一個允許對其數據進行修改的指針。 不好,很危險。
在第二種情況下,您將使用一個非常量指針,並將其分配給一個指針,該指針可能比原始指針產生更少的麻煩。 您不會對任何有害,非法或未定義的行為敞開大門。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.