引用在c。与方括号和索引,而不是结构域。和 - &GT ;? [英] referencing struct fields in c with square brackets and an index instead of . and ->?

查看:126
本文介绍了引用在c。与方括号和索引,而不是结构域。和 - &GT ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个结构,如:

Assuming I have a structure such as:

typedef struct
{
    char * string1;
    char * string2;
} TWO_WORDS;

,使得所有的字段都是相同类型的,并且我主要具有

such that all the fields are of the same type, and my main has

TWO_WORDS tw;

我可以参考使用TW [0]和字符串2字符串1两[1]?如果是这样的:

can I reference string1 with tw[0] and string2 with two[1]? If so:


  • 是C标准的这一部分?

  • 请我一定要在第一个结构转换为一个数组?

  • 有关这是在内存大小不同的领域是什么

  • 哪些是不同的类型,但什么样的字段大小相同?

  • 您可以做一个结构中指针运算?

  •   -
  • is this part of the c standard?
  • do i have to cast the struct to an array first?
  • what about fields which are different sizes in memory
  • what about fields which are different types but the same size?
  • can you do pointer arithmetic within a structure?
  • -

推荐答案

我得到了pretty接近此构造:

I got pretty close with this construct:

((char**)&tw)[0];

作为一个例子:

int main()
{
    typedef struct
    {
        char * string1;
        char * string2;
    } TWO_WORDS;

    TWO_WORDS tw = {"Hello", "World"};

    printf("String1: %s\n", ((char**)&tw)[0]);
    printf("String2: %s\n", ((char**)&tw)[1]);

    return 0;
}

不保证工作,因为编译器可以在字段之间添加填充。 (许多编译器有一个的#pragma 将避免结构的填充)

要回答你的每一个问题:


  • 是C标准的这一部分?

我一定要在结构转换为数组第一?

do i have to cast the struct to an array first? YES

有关这是在内存大小不同的领域是什么
可以用更做恶铸造和指针的数学

what about fields which are different sizes in memory
This can be done with even more "evil" casting and pointer-math

有关字段这是不同类型,但同样大小的是什么?
可以有更多的工作要做邪恶的铸造和指针的数学

what about fields which are different types but the same size?
This can be done with even more "evil" casting and pointer-math

您可以做一个结构中指针运算?
(不能保证总是工作正如您所料,但结构只是一块内存您可以用指针和指针运算访问)

can you do pointer arithmetic within a structure?
Yes (not guaranteed to always work as you might expect, but a structure is just a piece of memory that you can access with pointers and pointer-math)

这篇关于引用在c。与方括号和索引,而不是结构域。和 - &GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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