将结构复制到C中的结构 [英] Copy struct to struct in C

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

问题描述

我想将一个相同的结构复制到另一个结构中,然后将其用作与第一个结构的比较.问题是当我这样做时,我的编译器会给我一个警告!我应该以其他方式做还是我做错了:

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:

在头文件中:

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

在 C 文件中:

struct RTCclk RTCclk;
struct RTCclk RTCclkBuffert;

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

推荐答案

对于简单的结构,你可以像你一样使用 memcpy,或者只是从一个分配到另一个:

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.

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

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天全站免登陆