struct image_struct {
unsigned int width;
unsigned int height;
char mode;
char depth;
unsigned char data[13];
}
image_struct* newImage( unsigned int width, unsigned int height, char depth ) {
image_struct* image = (image_struct*)malloc(
sizeof(image_struct) - 13 + width * height * depth );
return( image );
}
Visual Studio doesn’t complain about accessing the fixed array beyond the 13 bytes, is this inadvisable? My intent was to avoid processing headers in file IO by using straight memory writes for structs with built-in headers. Apologies for the title. :\
There’s a trick you can do where you define a zero-length array at the end of a struct. You can then allocate the
sizeofthe struct plus the size of the array you want and you get an array of any size you want, decided at run-time rather than compile-time. Here is some info on it:http://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html
Points to note:
You must allocate the right amount of memory. You may be able to access the memory beyond the struct even if you didn’t allocate it. But that’s a bug in your code. The memory may be used for something else, or cross a boundary etc. Worst case it’ll overwrite some other data and you won’t discover it until some other part of your program behaves oddly. Never use heap memory you didn’t allocate.
Once allocated you cannot resize the array without
reallocing the entire struct + array size.The array has to be the last element of the array
Make sure you know how long the array is meant to be. Maybe store the length in a field in the struct and do your own bounds checking to ensure you don’t go wrong with your pointer arithmetic (/array index access).
This only applies to structs allocated on the heap, not automatic variables on the stack.