Constructor for structs in C

前端 未结 6 1216
南旧
南旧 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:43

    In C I typically create a function in the style of a constructor which does this. For example (error checking omitted for brevity)

    Object* Object_new(int id, int value) { 
      Object* p = malloc(sizeof(Object));
      p->id = id;
      p->value = value;
      return p;
    }
    
    ...
    Object* p1 = Object_new(id++, myValue);
    

提交回复
热议问题