代码之家  ›  专栏  ›  技术社区  ›  Kenji Baheux

将C中的“BigStruct”强制转换为“SmallStruct”(具有不同大小静态数组的类似结构)

  •  4
  • Kenji Baheux  · 技术社区  · 15 年前

    假设由于某种原因,您只能在C程序中使用静态内存。 我有一个基本结构,我在以下几个地方使用:

    #define SMALL_STUFF_MAX_SIZE 64
    
    typedef struct {
        /* Various fields would go here */
        ...
        double data[SMALL_STUFF_MAX_SIZE]; /* array to hold some data */
    } SmallStuff;
    

    现在,我被要求添加一个新特性,这导致了一种特殊情况,即我需要相同的结构,但需要一个更大的数组。由于内存太紧,我无法将SmallStuff结构的数组最大化。因此,我制作了一个特殊版本的结构,定义如下,当调用需要指向SmallStuff结构的指针的函数时(在这些函数中正确处理“数据”的实际大小),我最终将其转换为(SmallStuff*)

    #define BIG_STUFF_MAX_SIZE 1000000
    typedef struct {
        /* Various fields, identical to the ones in SmallStuff would go here */
        ...
        double data[BIG_STUFF_MAX_SIZE]; /* array to hold some data */
    } BigStuff;
    

    有什么副作用我应该考虑吗? 还是更好的方法来处理这类问题?

    提前谢谢。

    3 回复  |  直到 15 年前
        1
  •  3
  •   Variable Length Coder    15 年前

    你所做的一切都很好,尽管它往往会吓唬那些对指针和投法感到不舒服的人。

    typedef struct
    {
      // the usual
    
      size_t data_length;
      double *data;
    } Stuff;
    
    
    double bigdata[BIG_STUFF_MAX_SIZE];
    Stuff big = { ..., BIG_STUFF_MAX_SIZE, bigdata };
    
        2
  •  1
  •   Keith Randall    15 年前
    typedef struct {
        /* Various fields would go here */
        double data[]; /* a flexible array (C99 extension) */
    } AnySizeStuff;
    
    typedef struct {
      AnySizeStuff header;
      double smalldata[SMALL_STUFF_MAX_SIZE];
    } SmallStuff;
    
    typedef struct {
      AnySizeStuff header;
      double bigdata[BIG_STUFF_MAX_SIZE];
    } BigStuff;
    

    然后,如果x是SmallStuff或bigsuff,则可以通过&x、 头到例程,这些例程可以采取以下两种方式之一。

        3
  •  0
  •   Andrew Keith    15 年前

    虽然它的代码因为复杂而难看,但不应该有任何运行时问题,因为大小是硬编码的。