Default values in a C Struct

前端 未结 10 1637
闹比i
闹比i 2020-11-29 16:59

I have a data structure like this:

    struct foo {
        int id;
        int route;
        int backup_route;
        int current_route;
    }

and a

10条回答
  •  鱼传尺愫
    2020-11-29 17:27

    I'm rusty with structs, so I'm probably missing a few keywords here. But why not start with a global structure with the defaults initialized, copy it to your local variable, then modify it?

    An initializer like:

    void init_struct( structType * s )
    {
       memcopy(s,&defaultValues,sizeof(structType));
    }
    

    Then when you want to use it:

    structType foo;
    init_struct( &foo ); // get defaults
    foo.fieldICareAbout = 1; // modify fields
    update( &foo ); // pass to function
    

提交回复
热议问题