簡體   English   中英

C:指針類型之間的非法轉換:指向const unsigned char的指針 - >指向unsigned char的指針

[英]C: Illegal conversion between pointer types: pointer to const unsigned char -> pointer to unsigned char

以下代碼生成警告:

const char * mystr = "\r\nHello";
void send_str(char * str);

void main(void){
    send_str(mystr);
}
void send_str(char * str){
    // send it
}

錯誤是:

Warning [359] C:\main.c; 5.15 illegal conversion between pointer types
pointer to const unsigned char -> pointer to unsigned char

如何在沒有警告的情況下將代碼更改為編譯? send_str()函數還需要能夠接受非const字符串。

(我正在使用Hi-Tech-C編譯器編譯PIC16F77)

謝謝

您需要添加強制轉換,因為您將常量數據傳遞給“我可能會更改此”的函數:

send_str((char *) mystr);  /* cast away the const */

當然,如果函數確實決定更改實際上應該是常量的數據(例如字符串文字),那么您將獲得未定義的行為。

不過,也許我誤解了你。 如果send_str()永遠不需要改變它的輸入,但可能在調用者的上下文中使用非常量的數據調用 ,那么你應該只使用參數const因為它只是說“我不會改變它”:

void send_str(const char *str);

使用常量和非常量數據可以安全地調用它:

char modifiable[32] = "hello";
const char *constant = "world";

send_str(modifiable);  /* no warning */
send_str(constant);    /* no warning */

更改以下行

void send_str(char * str){
// send it
}

void send_str(const char * str){
// send it
}

你的編譯器說你的發送被轉換為char指針的const char指針。 在函數send_str更改其值可能會導致未定義的行為。(大多數情況下調用和調用函數不會由同一個人編寫,其他人可能會使用您的代碼並調用它來查看不正確的原型。)

暫無
暫無

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

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