为什么要使用结构的第一个元素的地址,而不是struct本身将? [英] Why use address of first element of struct, rather than struct itself?

查看:326
本文介绍了为什么要使用结构的第一个元素的地址,而不是struct本身将?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚降临在工作中的又一code基地,开发人员一致地使用结构的第一个元素的地址时,拷贝/比较/设置,而不是结构本身。这里有一个简单的例子。

I've just come upon yet another code base at work where developers consistently use the address of the first element of structs when copying/comparing/setting, rather than the struct itself. Here's a simple example.

首先有一个结构类型:

typedef struct {
    int a;
    int b;
} foo_t;

再有就是,使得这样一个结构的副本的功能:

Then there's a function that makes a copy of such a struct:

void bar(foo_t *inp)
{
    foo_t l;
    ...
    memcpy(&l.a, &inp->a, sizeof(foo_t));
    ...
}

我也不会自己写的memcpy 来电的方式和我开始了怀疑,原来的开发商根本没十分把握指针和结构用C不过,现在我已经看到了这两个不相关的code碱基,没有共同的开发者,所以我开始怀疑自己了。

I wouldn't myself write a call to memcpy in that way and I started out with suspecting that the original developers simply didn't quite grasp pointers and structs in C. However, now I've seen this in two unrelated code bases, with no common developers so I'm starting to doubt myself.

为什么一个想使用这种风格?

Why would one want to use this style?

推荐答案

没有人应该这样做。
如果重新排列结构成员你有麻烦了。

Nobody should do that. If you rearrange struct members you are in trouble.

这篇关于为什么要使用结构的第一个元素的地址,而不是struct本身将?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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