c - 当指向它的指针作为参数传递给函数时如何填充结构

标签 c linux operating-system

我有一个函数:

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/

相关文章:

c - 为什么在 o/p 中 i 的值不同

linux - DHCP 选项 77 - 格式错误的选项

用于运行 Virtual Box 的 Linux 低配置镜像

linux - 如何通过现有进程模拟高 CPU 峰值

go - CTRL + C 未被捕获

c - 如果我在C中输入超过数据类型范围的数字会发生什么?

c - 数据包嗅探器 : IP Header, 服务类型在 C 中输出 0

c++ - vector vector 的段错误

linux - Linux 的设备驱动程序文档

c - 二进制文件只有在创建指向它的符号链接(symbolic link)后运行时才能运行