使用的memcpy复制结构 [英] using memcpy to copy a structure

查看:191
本文介绍了使用的memcpy复制结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能显示的文件:结果
  复制一种结构到另一个结果
  复制一幅结构到另一个


 结构节点
        {
           INT N;
           结构分类密钥[M-1];
           结构节点* P [M]。
        } *根= NULL;

我创建newnode这类型的节点

 (* newnode) -  GT;键[I]

我想将数据复制到从结构clsf_ptr按键结构,这是同类型的也
我能做到这样,我不想初始化每个成员函数

 的memcpy((* newnode) -  GT;键[I],clsf_ptr)


解决方案

首先,应该可能是:

 的memcpy(及(newnode->键[I]),放大器; clsf_ptr,的sizeof(结构分类));

(假设 newnode 是一个指针到 - 节点 clsf_ptr 是一个classifier`)。

此外,结构的分配是在C法律,所以你可能只是这样做:

  newnode->键[I] = clsf_ptr;

请注意,这两种方式只能做浅拷贝 。所以,如果结构分类的内存指针,指针本身将被复制,而不是创造记忆的新副本。

Possible Duplicates:
copying one structure to another
Copying one structure to another

       struct node
        {
           int n; 
           struct classifier keys[M-1];
           struct node *p[M];
        }*root=NULL;

i have created newnode which is of type node

        (*newnode)->keys[i]

i want to copy data to keys structure from structure clsf_ptr which is also of same type can i do it like this,i don't want to initialize each member function

       memcpy((*newnode)->keys[i], clsf_ptr) 

解决方案

For a start, that should probably be:

memcpy(&(newnode->keys[i]), &clsf_ptr, sizeof(struct classifier));

(assuming newnode is a pointer-to-node, and clsf_ptr is a classifier`).

Also, struct assignment is legal in C, so you could just do:

newnode->keys[i] = clsf_ptr;

Note that both of these approaches only do a shallow copy. So if struct classifier has pointers to memory, the pointers themselves will be copied, rather than creating new copies of the memory.

这篇关于使用的memcpy复制结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆