簡體   English   中英

要返回指向struct的指針還是將其傳遞?

[英]To return a pointer to struct or pass it in?

其中哪一個是更有效和更好的代碼? 還是我應該采取其他方法?

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

謝謝! 對於任何錯別字,我深表歉意。

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_new (即foo_newnew_foo更常見)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM