1
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 は 13 バイトを超える固定配列へのアクセスについて不平を言いませんが、これはお勧めできませんか? 私の意図は、組み込みヘッダーを持つ構造体に直接メモリ書き込みを使用することにより、ファイル IO でヘッダーを処理することを回避することでした。タイトル失礼します。:\

4

1 に答える 1

1

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 sizeof the 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:

  1. 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.

  2. Once allocated you cannot resize the array without reallocing the entire struct + array size.

  3. The array has to be the last element of the array

  4. 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.

于 2012-07-05T18:40:04.943 に答える