将数组作为结构访问* [英] Accessing array as a struct *

查看:45
本文介绍了将数组作为结构访问*的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我认为应该起作用的其中之一,但最好检查问题。它可以在我的机器上编译并正常工作。



这是否可以保证达到我的期望(即,允许我访问数组的前几个元素,并保证

  struct somethingStruct 
{
int a;
int b;
int c;
};


void f()
{
int ThingsArray [5];
struct somethingStruct * thingsStruct =(struct somethingStruct *)& thingsArray [0];

ThingsArray [0] = 100;
ThingsArray [1] = 200;
ThingsArray [2] = 300;

printf(%d,ThingsStruct-> a);
printf(%d,ThingsStruct-> b);
printf(%d,ThingsStruct-> c);
}

编辑:为什么我要做这样的事情?我有一个映射到文件的数组。我将数组的第一部分视为标头,其中存储了有关数组的各种信息,其余部分则作为普通数组处理。如果将结构指向数组的开头,则可以将头数据作为结构成员进行访问,这更具可读性。结构中的所有成员都将与数组具有相同的类型。

解决方案

虽然我经常看到这一点,但您



不能解释结构的二进制布局,因为它可能在字段之间填充。



.lang.c常见问题解答: http://c-faq.com/struct/padding.htmls


This is one of those I think this should work, but it's best to check questions. It compiles and works fine on my machine.

Is this guaranteed to do what I expect (i.e. allow me to access the first few elements of the array with a guarantee that the layout, alignment, padding etc of the struct is the same as the array)?

struct thingStruct
{
    int a;
    int b;
    int c;
};


void f()
{
    int thingsArray[5];
    struct thingStruct *thingsStruct = (struct thingStruct *)&thingsArray[0];

    thingsArray[0] = 100;
    thingsArray[1] = 200;
    thingsArray[2] = 300;

    printf("%d", thingsStruct->a);
    printf("%d", thingsStruct->b);
    printf("%d", thingsStruct->c);
}

EDIT: Why on earth would I want to do something like this? I have an array which I'm mmapping to a file. I'm treating the first part of the array as a 'header', which stores various pieces of information about the array, and the rest of it I'm treating as a normal array. If I point the struct to the start of the array I can access the pieces of header data as struct members, which is more readable. All the members in the struct would be of the same type as the array.

解决方案

While I have seen this done frequently, you cannot (meaning it is not legal, standard C) make assumptions about the binary layout of a structure, as it may have padding between fields.

This is explained in the comp.lang.c faq: http://c-faq.com/struct/padding.htmls

这篇关于将数组作为结构访问*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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