繁体   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