C/C ++指向POD结构的指针也指向第一个结构成员 [英] C/C++ Pointer to a POD struct also points to the 1st struct member

查看:80
本文介绍了C/C ++指向POD结构的指针也指向第一个结构成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以假定C/C ++结构指针将始终指向第一个成员吗?
范例1:

Can I assume that a C/C++ struct pointer will always point to the first member?
Example 1:

typedef struct {
 unsigned char  array_a[2];
 unsigned char  array_b[5];
}test;
//..
test var;
//..

在上面的示例中,& var是否总是指向array_a?同样在上面的示例中,可以强制转换指针到一个无符号的char指针并分别访问每个字节?
示例2:

In the above example will &var always point to array_a? Also in the above example is it possible to cast the pointer to an unsigned char pointer and access each byte separately?
Example 2:

function((unsigned char *)&var,sizeof(test));
//...
//...
void function(unsigned char *array, int len){
 int i;
 for( i=0; i<len; i++){
    array[i]++;
 }
}

可以正常工作吗?

注意:我知道char在一个结构中是按字节对齐的,因此我假设上述结构的大小为7个字节.

Note: I know that chars are byte aligned in a struct therefore I assume the size of the above struct is 7 bytes.

推荐答案

对于C结构,是的,您可以依靠它.这就是几乎所有面向对象"样式的API如何在C中工作的方式(例如GObject和GTK).

For C structs, yes, you can rely on it. This is how almost all "object orientated"-style APIs work in C (such as GObject and GTK).

对于C ++,您只能将其用于普通旧数据"(POD)类型,这些类型必须保证与C结构相同地放置在内存中.确切地说,构成POD类型的东西有点复杂,并且在C ++ 03和C ++ 11之间发生了变化,但是关键是如果您的类型具有任何虚函数,那么它就不是POD.

For C++, you can rely on it only for "plain old data" (POD) types, which are guaranteed to be laid out in memory the same way as C structs. Exactly what constitutes a POD type is a little complicated and has changed between C++03 and C++11, but the crux of it is that if your type has any virtual functions then it's not a POD.

(在C ++ 11中,您可以使用 std :: is_pod 在编译时测试结构是否为POD类型.)

(In C++11 you can use std::is_pod to test at compile-time whether a struct is a POD type.)

这将告诉您在C ++中什么构成POD类型: http://en.cppreference.com/w/cpp/concept/PODType

This tells you what constitutes a POD type in C++: http://en.cppreference.com/w/cpp/concept/PODType

实际上,在C ++ 11中,它不一定是POD,而只是标准布局",这是一个稍弱的条件.标准的第9.2节[class.mem]第20段:

Actually, in C++11, it doesn't need to be a POD, just "standard layout", which is a lightly weaker condition. Quoth section 9.2 [class.mem] paragraph 20 of the standard:

指向标准布局结构对象的指针(使用reinterpret_cast进行适当转换)指向其初始成员(如果该成员是位字段,则为它所在的单元),反之亦然.[ 笔记:因此,在标准布局结构对象中可能存在未命名的填充,但在其开始时没有,根据需要实现适当的对齐.—尾注]

A pointer to a standard-layout struct object, suitably converted using a reinterpret_cast, points to its initial member (or if that member is a bit-field, then to the unit in which it resides) and vice versa. [ Note: There might therefore be unnamed padding within a standard-layout struct object, but not at its beginning, as necessary to achieve appropriate alignment. — end note ]

这篇关于C/C ++指向POD结构的指针也指向第一个结构成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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