How to initialize const members of structs on the heap

前端 未结 4 1980
忘了有多久
忘了有多久 2020-12-12 23:58

I would like to allocate a structure on the heap, initialize it and return a pointer to it from a function. I\'m wondering if there\'s a way for me to initialize const membe

4条回答
  •  误落风尘
    2020-12-13 00:44

    I like caf's approach, but this occured to me too

    ImmutablePoint* newImmutablePoint(int x, int y){ 
       struct unconstpoint {
          int x;
          int y;
       } *p = malloc(sizeof(struct unconstpoint));
       if (p) { // guard against malloc failure
          *p.x = x;
          *p.y = y;
       }
       return (ImmutablePoint*)p;
    }
    

提交回复
热议问题