c++ - Nice representation of byte array and its size -


how represent byte array , size nicely? i'd store (in main memory or within file) raw byte arrays(unsigned chars) in first 2/4 bytes represents size. operations on such array not well:

void func(unsigned char *bytearray) {   int size;   memcpy(&size, bytearray, sizeof(int));   //rest of operation when know bytearray size } 

how can avoid that? think simple structure:

struct bytearray {   int size;   unsigned char *data; };  bytearray *b = reinterpret_cast<bytearray*>(new unsigned char[10]); b->data = reinterpret_cast<unsigned char*>(&(b->size) + 1); 

and i've got access size , data part of bytearray. still looks ugly. recommend approach?

you're re-inventing "pascal string". however

 b->data = reinterpret_cast<unsigned char*>(&(b->size) + 1); 

won't work @ all, because pointer points itself, , pointer overwritten.

you should able use array unspecified size last element of structure:

struct bytearray {   int size;   unsigned char data[]; };  bytearray *b = reinterpret_cast<bytearray*>(::operator new(sizeof (bytearray) + 10)); b->size = 10;  //...  ::operator delete(b); 

unlike std::vector, stores size , data together, can, example, write file in 1 operation. , memory locality better.

still, fact std::vector tested , many useful algorithms implemented makes attractive.


Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -