References to structural fields in c with square brackets and an index instead. and ->?

Assuming I have a structure like:

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

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

TWO_WORDS tw;

Is it possible to refer to string1 with tw [0] and string2 with two [1]? If yes:

  • Is this part of standard c?
  • Do I need to pass the structure to an array first?
  • how about fields with different sizes in memory
  • how about fields of different types but the same size?
  • Can you do pointer arithmetic inside a structure? -
+5
source share
7 answers

I really liked this design:

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

As an example:

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;
}

Operation is not guaranteed, since the compiler can add padding between fields. (Many compilers have #pragmathis to avoid filling structures)

:

  • - c?

  • ?


  • " " -

  • , ?
    " " -

  • ?
    ( , , , - , -)

+3

@ouah, , . :

typedef union
{ char *a[2];
  struct
  { char *string1;
    char *string2;
  } s;
} TWO_WORDS;

TWO_WORDS t;

t.a[0] = ...;
t.a[1] = ...;
t.s.string1 = ...;
t.s.string2 = ...;
+4

, , .

++ ++, "- ". C , offsetof .

.

const size_t TW_OFFSETS[] = 
  { offsetof(TWO_WORDS, string1), offsetof(TWO_WORDS, string2) };

*(char **)((char *) &tw + TW_OFFSETS[i]); 
/* Provides lvalue access to either `tw.string1` or `tw.string2` depending on 
   the value of `i` */

( ), , C.

,

 #define TW_MEMBER(T, t, i) *(T *)((char *) &(t) + TW_OFFSETS[i])

 TW_MEMBER(char *, tw, 0) = "Hello";
 TW_MEMBER(char *, tw, 1) = "World";

 for (int i = 0; i < 2; ++i)
   printf("%s\n", TW_MEMBER(char *, tw, i));

, , , char*[2] ( , ). , . offsetof .

+3

1 tw [0] string2 [1]?

, C, tw , .

[] , .

string1, : tw.string1

+2

, C. C .

, , , .

? , ?

+1

((char **)&tw)[0] , , tw[0].

+1

struct, , , union, , . , . , , , , .

struct quad_int {int n0; int n1; int n2; int n3;}
union quad_int_union {struct pair p; int n[4];}

union quad_int_union my_thing;

my_thing.n[0] is synonymous with my_thing.p.n0
my_thing.n[1] is synonymous with my_thing.p.n1
etc.

0

All Articles