Constructor for structs in C

前端 未结 6 1330
南旧
南旧 2021-02-01 01:48

Given:

struct objStruct {
    int id;
    int value;
};

typedef struct objStruct Object;

Is there a shortcut to allocate and initialize the ob

6条回答
  •  忘掉有多难
    2021-02-01 02:50

    struct thingy {
       char * label;
       int x;
    };
    
    #define declare_thingy( name, label, val) struct thingy name = { label, val }
    
    struct thingy * new_thingy(const char * label, int val) {
         struct thingy * p = malloc(sizeof(struct thingy));
         if (p) {
              p->label = label;
              p->val = val;
         }
         return p;
    }
    

提交回复
热议问题