是结构名称指向第一个元素? [英] Are struct names pointers to first element?

查看:139
本文介绍了是结构名称指向第一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一些类似的问题,但没有人帮助很多。是结构名称指向该结构的第一要素,类似于一个数组?

I found a few similar questions but none of them helped much. Are struct names pointers to the first element of the struct, similar to an array?

struct example {
    int foo;
    int bar;
};

struct example e;
e.foo = 5;
e.bar = 10;
printf("%d\n%d\n%d\n%d\n%d\n%d\n", e, e.foo, e.bar, &e, &e.foo, &e.bar);

输出:

5
5
10
2033501712
2033501712
2033501716

所有答案的其他问题说不,但这个产量混淆了我。所有帮助将大大AP preciated。

All of the answers to the other questions said "no", but this output confuses me. All help would be greatly appreciated.

推荐答案

结构的确是第一个元素的地址,但你需要的地址知道元素的类型,以便安全地投放。

The address of a struct is indeed the address of the first element, though you'll need to know the type of the element in order to safely cast it.

(C1X§6.7.2.1.13:一个指向结构对象,适当
  转换后,指出了其最初的成员​​......反之亦然。也有可能
  是内,结构对象,但不能以无名填充其
  开始。)

(C1x §6.7.2.1.13: "A pointer to a structure object, suitably converted, points to its initial member ... and vice versa. There may be unnamed padding within as structure object, but not at its beginning.")

虽然它是一种丑陋,生产软件无数件靠这个。 QNX,例如,写的资源管理器时,使用这种开放式控制块(OCB)逻辑的行为。 GTK也类似。

While it's kind of ugly, numerous pieces of production software rely on this. QNX, for example, uses this kind of behavior in open control block (OCB) logic when writing resource managers. Gtk also something similar.

您目前的实现是很危险的,但。如果必须依靠此行为,做到像这样,不要试图传递一个指针到结构作为参数传递给的printf(),因为你再破故意用最少的类型安全的语言的一个特征。

Your current implementation is dangerous though. If you must rely on this behavior, do it like so, and don't attempt to pass a pointer-to-struct as an argument to printf(), as you're intentionally breaking a feature of a language with minimal type-safety.

struct example {
    int foo;
    int bar;
};

struct example myStruct = { 1, 2 };
int* pFoo = (int*)&myStruct;
printf("%d", *pFoo);

最后,这仅适用于第一个元素。后续元素可能不是,你期望他们的情况,即由于结构包装和填充

这篇关于是结构名称指向第一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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