使得无论“插入字节”和“删除字节”通过与正/负偏移
问题描述:
我有两个操作“插入字节”的工作,基本上都是相同的:使得无论“插入字节”和“删除字节”通过与正/负偏移
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行正负值检查?
答
不......你的删除函数不知道之前malloc已经有多少。
- 如果您制作了C++(标记为C)类,则可以封装当前大小。
- 你可以做一个函数:resize(from,current_size,delta)这将工作。
current_size可从外面,并计划在C++中也使用..好吧,谢谢你提醒这个东西..感觉更清晰:) – 2011-01-31 02:22:20