复制结构在C结构体 [英] Copy struct to struct in C

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

问题描述

欲相同结构复制到另一个并稍后把它作为一个comparance到的第一个。问题是,我的编译器给了我一个警告,当Im做这个样子!我应该做它以另一种方式或我在做这个错误:

在头文件:

 的extern结构RTCCLK
{
uint8_t有第二次;
uint8_t有分钟;
uint8_t有小时;
uint8_t有MDAY;
uint8_t有一个月;
uint8_t有一年;
}
RTCCLK;

在C文件:

 结构RTCCLK RTCCLK;
结构RTCCLK RTCclkBuffert;无效FunctionDO(无效)
{
   ... //一些code
   / *第一个结构值复制到第二个* /
   的memcpy(安培; RTCCLK,&安培; RTCclkBuffert,sizeof的RTCCLK);
}


解决方案

对于简单的结构,您可以使用的memcpy 像你一样,或者只是从一个分配给其他

  = RTCCLK RTCclkBuffert;

编译器将创建code复制结构适合你。


有关复制的重要说明:这是一个浅拷贝,就像的memcpy 。这意味着,如果你有例如包含指针的结构,它只是将被复制,而不是它们指向什么实际的指针,所以副本后,你将有两个指针指向相同的内存。

I want to copy an identical struct into another and later on use it as a comparance to the first one. The thing is that my compiler gives me a warning when Im doing like this! Should I do it in another way or am I doing this wrong:

In header File:

extern struct RTCclk
{
uint8_t second;
uint8_t minute;
uint8_t hour;
uint8_t mday;
uint8_t month;
uint8_t year;
}
RTCclk;

In C file:

struct RTCclk RTCclk;
struct RTCclk RTCclkBuffert;

void FunctionDO(void)
{
   ... // Some Code
   /* Copy first struct values into the second one */
   memcpy(&RTCclk, &RTCclkBuffert, sizeof RTCclk);
}

解决方案

For simple structures you can either use memcpy like you do, or just assign from one to the other:

RTCclk = RTCclkBuffert;

The compiler will create code to copy the structure for you.


An important note about the copying: It's a shallow copy, just like with memcpy. That means if you have e.g. a structure containing pointers, it's only the actual pointers that will be copied and not what they point to, so after the copy you will have two pointers pointing to the same memory.

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

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