[英]Join two unsigned chars + mallock u_chars
如何正確分配一組未簽名的字符?
packet = (u_char*) malloc (20*sizeof(u_char)); //is it simmilar to u_char packet[20]?
我有2個函數,聲明如下
u_char *frame(bool type, char* srcmac, char* dstmac);
u_char *ip(bool type, char* srcip, char* dstip);
如何連接這兩個未簽名的字符? 我嘗試了memcpy,strcat [僅用於char]。
u_char *concat(u_char *s1, u_char *s2) {
u_char *result = (u_char*) malloc((sizeof(s1)+sizeof(s2)+1));//+1 for the zero-terminator
memcpy(result, s1, sizeof(s1));
memcpy(result, s2, sizeof(s2)); //I am overwriting result already and sizeof is size of pointer...
return result;
}
你有:
u_char *concat(u_char *s1, u_char *s2) {
u_char *result = (u_char*) malloc((sizeof(s1)+sizeof(s2)+1));
這沒有任何意義。 您為什么關心指針有多大? 在不知道它們有多大的情況下,該函數應如何將它們串聯起來? 也:
memcpy(result, s1, sizeof(s1));
memcpy(result, s2, sizeof(s2));
應該:
memcpy(result, s1, s1_size);
memcpy(result + s1_size, s2, s2_size);
您必須自己跟蹤s1
和s2
對象的大小。 我稱這些變量為s1_size
和s2_size
,但它們可以是常量。 不要在指針上使用sizeof
,否則會得到指針的大小。 sizeof
函數告訴您類型的大小,該大小在編譯時已知。
由於這是C ++,為什么不只使用std::vector<unsigned char>
,然后+
和+=
會很好地工作。 否則,考慮struct
封裝兩個指針和為size_t。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.