2011-01-31 74 views
0

我有兩個操作「插入字節」的工作,基本上都是相同的:使得無論「插入字節」和「刪除字節」通過與正/負偏移

insert_bytes(from, count) 
delete_bytes(start, stop) -> delete_bytes(from, count) 

insert_bytes實現示例:

unsigned char* new_bytes = (unsigned char*)malloc((old_length+count)*sizeof(unsigned char)); 
memcpy(new_bytes, old_bytes, from); // negative value can't go to from here 
memcpy(new_bytes+count, old_bytes+from, old_length-from); 
return new_bytes+from; // pointer to write 

是否有任何安全的方式來實現delete_bytes作爲insert_bytes(帶有負偏移)的調用而不寫5-6行正負值檢查?

回答

1

不......你的刪除函數不知道之前malloc已經有多少。

  • 如果您製作了C++(標記爲C)類,則可以封裝當前大小。
  • 你可以做一個函數:resize(from,current_size,delta)這將工作。
+0

current_size可從外面,並計劃在C++中也使用..好吧,謝謝你提醒這個東西..感覺更清晰:) – 2011-01-31 02:22:20