[英]Convert unsigned char array with int to unsigned char
有人可以幫我解決以下錯誤嗎? 我可以在嘗試通過buf
之前先投len
嗎?
int len=2;
unsigned char tmp[len + 1];
unsigned char * buf = &tmp;
錯誤是:
error: cannot convert 'unsigned char (*)[(((unsigned int)((int)len)) + 1)]' to 'unsigned char*' in assignment
如果只需要指向數組的指針,請使用
unsigned char * buf = tmp;
順便說一句,您聲明tmp
的方式使其成為可變長度數組 (VLA)。 從技術上講,盡管許多編譯器都支持VLA作為擴展,但是C ++不允許使用這些 。
問題不在於len
。 問題是您試圖獲取數組的地址,而不是數組的第一個元素的地址。 類型根本不匹配。
代替:
unsigned char* buf = &tmp[0];
另外,數組名稱(FSVO“方便地”)很方便地衰減為&tmp[0]
,因此您可以簡單地編寫:
unsigned char* buf = tmp;
另外,您目前沒有為數組的維數使用常量值-確保將len
為const
並使用常量值初始化。 在C ++ 11,this'd更好地constexpr
要真正確保你不小心嘗試使用GCC沃拉斯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.