sfi
sfi

Reputation: 146

To return a pointer to struct or pass it in?

Which of these is more efficient and better code? or is there some other way I should be doing this?

typedef struct foo {
int width;
int height;
} foo;

...this typedef in both the below examples, but its really an arbitrary structure...

foo *new_foo (int width, int height) {

  foo *f
  if ((f = malloc(sizeof(foo)))==NULL) return NULL;

  f->width = width;
  f->height = height;

  return foo;
}  


void del_foo (foo *f) {free(f);}


int main () {

  int width = 3;
  int height = 4; // arbitrary values

  foo *f   
  f = new_foo(width, height)

  // do something with foo here      

  del_foo(f);
}

or

int new_foo (foo *f, int width, int height) {

  f->width = width;
  f->height = height;

  return 0;
}  


int main () {

  int width = 3;
  int height = 4; // arbitrary values

  foo *f
  if ((f = malloc(sizeof(foo)))==NULL) return NULL;   
  new_foo(f, width, height)

  // do something with foo here      

  free(f);
}

Thanks! My apologies for any typos.

Upvotes: 0

Views: 121

Answers (1)

simonc
simonc

Reputation: 42165

foo* new_foo(int width, int height)

seems preferable for a function with new in its name (new will imply dynamic allocation to people with experience of C++).

void foo_init(foo f, int width, int height)

would be reasonable if you wanted to allow clients to declare foo objects on the stack as well as heap. You could also choose to provide both, implementing new_foo as a malloc then a call to foo_init.

If you provide a function which allocates memory, it'd be reasonable to also offer a function which destroys an object - foo_destroy(foo ) (del_foo in your question?)

One last, minor, point - you can more obviously group related functions if you prefix their names the struct they operate on rather than adding the struct at the end (i.e. foo_new is more usual than new_foo)

Upvotes: 1

Related Questions