fork download
  1. #include <stdio.h>
  2.  
  3.  
  4. struct expensive; // Forward declaration, ignore
  5. // One could also use a struct expensive * (a pointer) instead
  6. // of this structure. IMO giving it a name is the better option.
  7. struct expensive_handle {
  8. struct expensive * target;
  9. };
  10.  
  11. // Store the simple data members as usual, store a pointer to a
  12. // handle (pointer) to the expensive ones
  13. struct my_struct {
  14. int simple;
  15. struct expensive_handle * handle;
  16. };
  17.  
  18. struct expensive {
  19. int content; // whatever
  20. };
  21.  
  22.  
  23. struct my_struct * new() {
  24. struct my_struct * data = malloc(sizeof(*data));
  25. // Error handling please
  26. // Set simple data members
  27. data->handle = malloc(sizeof(*(data->handle)));
  28. // Error handling please
  29. data->handle->target = NULL;
  30. return data;
  31. }
  32.  
  33. int get_expensive(struct my_struct const * ptr) {
  34. if (ptr->handle->target == NULL) {
  35. ptr->handle->target = malloc(sizeof(struct expensive));
  36. // Error handling please
  37. puts("A hell of a computation just happened!");
  38. ptr->handle->target->content = 42; // WOO
  39. }
  40. return ptr->handle->target->content;
  41. }
  42.  
  43. int main(void) {
  44. struct my_struct * p = new();
  45. printf("%d\n", get_expensive(p));
  46. printf("%d\n", get_expensive(p));
  47. }
  48.  
Success #stdin #stdout 0s 9424KB
stdin
Standard input is empty
stdout
A hell of a computation just happened!
42
42