[英]How to fill a structure when a pointer to it, is passed as an argument to a function
I have 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) */
}
}
}
The function which calls func(pw) is able to get the updated information.调用 func(pw) 的函数能够获取更新的信息。
But is it fine to use it as above.但是可以像上面那样使用它。 The statement *pw = *save is not a deep copy.
语句 *pw = *save 不是深拷贝。 I do not want to copy each and every member of structure one by one like pw->pw_shell = strdup(save->pw_shell) etc.
我不想像 pw->pw_shell = strdup(save->pw_shell) 等那样一一复制结构的每个成员。
Is there any better way to do it?有没有更好的方法来做到这一点?
Thanks.谢谢。
函数参数需要是struct passwd**
,然后更改*passwd
You can do a shallow copy if you like, but the result will only be good until the next call to getpenam.如果你愿意,你可以做一个浅拷贝,但结果只会在下一次调用 getpenam 之前是好的。 But why copy twice?
但是为什么要复制两次呢? Your malloc is a memory leak!
你的 malloc 是内存泄漏! This will do just fine:
这将做得很好:
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.
}
If you want the deep copy, you have to do it field by field:如果你想要深拷贝,你必须逐个字段地做:
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
}
For the deep copy, you need a corresponding routine to free the malloc()'ed storage:对于深拷贝,你需要一个相应的例程来释放 malloc() 的存储:
void free_passwd_fields(struct passwd *pw)
{
free(pw->pw_name);
free(pw->pw_passwd);
// etc
}
A nice way to do the call is:打电话的一个好方法是:
// 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.