簡體   English   中英

當指向結構的指針作為參數傳遞給函數時如何填充結構

[英]How to fill a structure when a pointer to it, is passed as an argument to a function

我有一個功能:

func (struct passwd* pw)
{

struct passwd* temp;
struct passwd* save;

temp = getpwnam("someuser");
/* since getpwnam returns a pointer to a static 
 * data buffer, I am copying the returned struct
 * to a local struct.
 */

if(temp) {
   save = malloc(sizeof *save);
   if (save) {
       memcpy(save, temp, sizeof(struct passwd));
       /* Here, I have to update passed pw* with this save struct. */
       *pw = *save; /* (~ memcpy) */
   }
}

}

調用 func(pw) 的函數能夠獲取更新的信息。

但是可以像上面那樣使用它。 語句 *pw = *save 不是深拷貝。 我不想像 pw->pw_shell = strdup(save->pw_shell) 等那樣一一復制結構的每個成員。

有沒有更好的方法來做到這一點?

謝謝。

函數參數需要是struct passwd** ,然后更改*passwd

如果你願意,你可以做一個淺拷貝,但結果只會在下一次調用 getpenam 之前是好的。 但是為什么要復制兩次呢? 你的 malloc 是內存泄漏! 這將做得很好:

void func (struct passwd *pw)
{
  struct passwd *tmp = getpenam("someuser"); // get a pointer to a static struct
  *pw = *tmp;  // copy the struct to caller's storage.
}

如果你想要深拷貝,你必須逐個字段地做:

void deep_func (struct passwd *pw)
{
  struct passwd *tmp = getpenam("someuser"); // get a pointer to a static struct
  *pw = *tmp; // copy everything
  pw->pw_name = safe_strdup(pw->pw_name);  // Copy pointer contents.
  pw->pw_passwd = safe_strdup(pw->pw_passwd);
  // etc for all pointer fields
}

對於深拷貝,你需要一個相應的例程來釋放 malloc() 的存儲:

void free_passwd_fields(struct passwd *pw)
{
  free(pw->pw_name);
  free(pw->pw_passwd);
  // etc
}

打電話的一個好方法是:

// Declare a 1-element array of structs.  
// No &'s are needed, so code is simplified, and a later change to malloc()/free() is very simple.
struct passwd pw[1];

// ... and later
func(pw);

// pw now behaves like a pointer to a struct, but with no malloc or free needed.
// For example:
printf("login name is %s\n", pw->pw_name);

// Done with copy.  Free it.
free_passwd_fields(pw);

暫無
暫無

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

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