0

I have a struct type and a variable with defined like this:

typedef struct test
{
    uint8_t            a;        
    uint8_t            b;            
    uint8_t            c;            
} test_type;


test_type x[2];

Does this make this variable to behave like a 2-dimension variable? I mean that when I call x[0], will it return the address of the 1st variable which have struct test_type defined above?

An Le
  • 128
  • 1
  • 8
  • 2
    `x[0]` is a `struct test`, not an address. – chux - Reinstate Monica Jul 26 '18 at 02:58
  • @chux Is this mean that I can't get the value of a by calling x[0]->a? – An Le Jul 26 '18 at 03:09
  • 2
    @AnLe What is preventing you from *trying* ? An no, you need the dot accessor for non-pointers. `x->a` would work, but only to access the first struct\ member `a`, and only because an array name in an expression converts to a temporary pointer to first element. – WhozCraig Jul 26 '18 at 03:11
  • 1
    You can access the value of a by call `x[0].a` – Programmer dude Jul 26 '18 at 03:15
  • I just feel confused cause I heard a friend said that 1-D variable with type struct would behave like a 2-D, I will check again. Thank you – An Le Jul 26 '18 at 03:16
  • 1
    Smack your friend -- he or she knows not of what they speak. `test_type x[2];` declares an array of `test_type` with 2 elements. (with indexes `0` and `1`). When accessing an array, the array variable is converted to a temporary pointer to the first element as @WhozCraig indicates. (which would lead you to think you would use `->` to access the members -- **but** the `[ ]` operator acts as a dereference so `x[0]` or `x[1]` is type `test_type` (or `struct test`) so you need to `'.'` (dot) operator to access the members. – David C. Rankin Jul 26 '18 at 03:46
  • thank, got it now, won't trust friends anymore lol – An Le Jul 26 '18 at 03:54

1 Answers1

1

The memory layout of the struct will be the same if it were a two-dimensional array i.e. a,b,c will be stored after one another in memory however you need to take care that the compiler does not insert padding between them. A real two-dimensional doesn't have that problem.

The compiler usually aligns structure members to natural address boundaries so depending on what size your variables have in the struct, it may insert extra bytes between the fields in the structure.

AndersK
  • 35,813
  • 6
  • 60
  • 86
  • Well, that is somewhat misleading, because a struct can contain members of differing types, but I understand what you are saying. The padding uncertainty is why the macro `offsetof` is included in `stddef.h`. So while memory layout may be similar to a 2D array from an ordering standpoint, access of the array-of-struct elements/members cannot be accessed as a 2D array. – David C. Rankin Jul 26 '18 at 04:32
  • yes, I agree, sorry if it didn't sound clear enough, as you say, the bottom line is that they are not the same only "somewhat" :) – AndersK Jul 26 '18 at 05:13