【问题标题】:To return a pointer to struct or pass it in?返回指向结构的指针或将其传入?
【发布时间】:2013-02-24 22:26:47
【问题描述】:

以下哪一个是更高效、更好的代码?还是有其他方法我应该这样做?

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

...下面两个示例中的这个 typedef,但它实际上是一个任意结构...

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);
}

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);
}

谢谢!对于任何错别字,我深表歉意。

【问题讨论】:

    标签: c function pointers struct


    【解决方案1】:
    foo* new_foo(int width, int height)
    

    对于名称中带有new 的函数似乎更可取(new 意味着动态分配给具有 C++ 经验的人)。

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

    如果您想允许客户端在堆栈和堆上声明 foo 对象,那将是合理的。您也可以选择同时提供两者,将new_foo 实现为malloc,然后调用foo_init

    如果你提供一个分配内存的函数,那么提供一个销毁对象的函数也是合理的 - foo_destroy(foo )(你的问题是del_foo?)

    最后一点,次要的一点 - 如果将它们的名称作为它们所操作的结构的前缀而不是在末尾添加结构(即foo_newnew_foo 更常见),您可以更明显地对相关函数进行分组。

    【讨论】:

    • 谢谢,抱歉,这里打错了,应该是“void foo_init(foo *f, int width, int height)”!
    • 好的,这是一个非常重要的错字!我已经用更多信息更新了我的答案
    • 非常感谢!并感谢您提供的小点、有趣和有用的信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-30
    • 1970-01-01
    • 2014-09-09
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多