微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

用C组织静态数据

我正在研究一些嵌入式软件,其中有一些关于“产品”的静态信息.由于某个产品的信息在执行期间永远不会改变,我想在编译时初始化这些数据结构,以节省堆栈/堆上的一些空间.

我为数据创建了一个Product类,打算在系统中创建大量的所有产品,然后在这个结构中进行查找,但我还没弄清楚如何让它工作.这些阵列给我带来了麻烦.一些伪代码

class Product {
    int m_price;
    int m_availability[]; // invalid,need to set a size
    ... etc

    // Constructor grabbing values for all members
    Product(int p,int a[],...);
}

static const Product products[] = 
{
    Product(99,{52,30,63,49},...),// invalid Syntax
    ...                    
}

有没有办法制作像这样的作品?我唯一能想到的是按属性组织并跳过整个Product对象.我觉得这会让整个事情更难理解和维护.

有没有人对如何最好地组织这类数据有任何建议?

谢谢.

解决方法

旧式C风格的静态结构阵列听起来非常符合您的要求.在编译时初始化,零运行时开销,不使用堆栈或堆. C仍然是嵌入式世界的主要参与者并非共同发生.

所以(一个配方 – 有足够的空间来改变这个细节);

// in .h file
    class Product {
    public: // putting this first means the class is really a struct
        int m_price;
        int m_availability[4]; 
        //.... (more)
    };
    extern const Product product_array[];
    extern const int     product_array_nbr;

// in .cpp file
    const Product product_array[] =
    {
        {
             23,{56,1,2,4},//....(more)
        },{
             24,{65,//....(more)
    };

    const int product_array_nbr = sizeof(product_array)/sizeof(product_array[0]);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐