C programming (declaration of structures)

When we declare that:

int array[2];

array = "Holds the address of the first 32 bits", i.e. he holds &array[0]. Thus, an "array" is a pointer. But when we declare a structure, for example:

typedef struct x 
{
    int y;
    int array[2];
}

Why is the size of this structure equal to 16 bytes? there shouldn't be 8 bytes since "array" is a pointer? Am I so confused?

+4
source share
4 answers

array , , . . , , , sizeof :

#include <stdio.h>
typedef struct x 
{
    int y;
    int array[2];
};

int main(void) {
    struct x test1;
    printf("sizeof(int) %zu \n", sizeof(int));
    printf("sizeof(test1) %zu \n", sizeof(test1));
    printf("sizeof(test1.array) %zu", sizeof(test1.array));
    return 0;
}

ideone 4, 12 8 . http://ideone.com/pKBe1X , , , , .

sizeof(test1.y) + sizeof(test1.array) != sizeof(test1), . - #pragma pack (ms ) __attribute__((__packed__)) (gcc), , .

​​ , ( 16 ) . Wikipedia .

+3

, :

int array[2];

array = " 32 ", & array [0].

. . 2- , - :

     +---+
arr: |   | arr[0]
     +---+ 
     |   | arr[1]
     +---+

, arr, 2- int, . arr ( "" ) " int".

struct :

       +---+
    y: |   | 
       +---+
array: |   | array[0]
       +---+
       |   | array[1]
       +---+

12 , array , 8 16 .

+2

, . , . .

a struct, , . int - int. , 32-, 12 ( 4- ints). , 8- ( ). 16 . , "" , . #pragma pack(0) .

+1

int char

#include <stdio.h>

#pragma  pack (push, 1)
typedef struct {
    int a;
    int b[2];
}TEST1;

typedef struct {
    int a;
    int b[2];
    char c;
}TEST2;
#pragma pack(pop)

typedef struct {
    int a;
    int b[2];
}TEST3;

typedef struct {
    int a;
    int b[2];
    char c;
}TEST4;

int main(){
    printf(" ==== PAKED =====\t==== DEFAULT =====\n");
    printf("sizeof(TEST1)=%d \tsizeof(TEST3)=%d\n",sizeof(TEST1),sizeof(TEST3));
    printf("sizeof(TEST2)=%d \tsizeof(TEST4)=%d\n\n",sizeof(TEST2),sizeof(TEST4));

   return 0;
}

(AMD 64 ;))

 ==== PAKED =====       ==== DEFAULT =====
sizeof(TEST1)=12        sizeof(TEST3)=12
sizeof(TEST2)=13        sizeof(TEST4)=16

Press any key to continue...
+1

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


All Articles