我有一个函数:
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
关于c - 当指向它的指针作为参数传递给函数时如何填充结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13373273/