Access to an array as a structure *

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

Is this guaranteed what I expect (for example, to allow me access to the first elements of the array with the guarantee that the layout, alignment, addition, etc. of the structure matches 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: - ? , mmapping . "", , - . , , . , .

+3
4

, ( , , C) , .

comp.lang.c faq: http://c-faq.com/struct/padding.htmls

+3

, , , , . , :

enum { HEADER_A, HEADER_B, HEADER_C };

/* ... */.

printf("%d", thingsArray[HEADER_A]);
printf("%d", thingsArray[HEADER_B]);
printf("%d", thingsArray[HEADER_C]);
+3

, , , ( , , , #pragma, , ), , , . C, .

: "?" . , . ? , .

+2

, :

struct header {
    long  headerData1;
    int   headerData2;
    int   headerData3;
    int   fileData[ 1 ];  // <- data begin here
};

struct header *myFileHeader ( )

myFileHeader->fileData[ position ]

position. , posistion ( ).

:, , , , , (, int 32 64 ...)

0
source

Source: https://habr.com/ru/post/1781704/


All Articles