How to initialize const members of structs on the heap

前端 未结 4 1973
忘了有多久
忘了有多久 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条回答
  •  萌比男神i
    2020-12-13 00:50

    If this is C and not C++, I see no solution other than to subvert the type system.

    ImmutablePoint * make_immutable_point(int x, int y)
    {
      ImmutablePoint *p = malloc(sizeof(ImmutablePoint));
      if (p == NULL) abort();
    
      // this 
      ImmutablePoint temp = {x, y};
      memcpy(p, &temp, sizeof(temp));
    
      // or this
      *(int*)&p->x = x;
      *(int*)&p->y = y;
    
      return p;
    }
    

提交回复
热议问题