How to use alignas specifier in struct with C

1 Answer

0 votes
#include <stdalign.h>
#include <stdio.h>
 
// every object of type struct account will be aligned to 16-byte boundary
struct account
{
    alignas(16) float account_arr[4];
};

// every object of type struct user will be aligned to 16-byte boundary
struct user
{
    alignas(16) float user_arr[6];
};
 
// every object of type struct data1 will be aligned to 128-byte boundary
struct data1
{
    char ch;
    alignas(128) char data1_arr[128];
};

// every object of type struct data2 will be aligned to 128-byte boundary
struct data2
{
    alignas(128) char data2_arr[128];
};
 
int main(void)
{
    printf("sizeof(account) = %zu\n", sizeof(struct account));
    printf("alignof(account) = %zu\n", alignof(struct account));
    
    printf("sizeof(user) = %zu\n", sizeof(struct user));
    printf("alignof(user) = %zu\n", alignof(struct user));

    printf("sizeof(data1) = %zu (1 byte + 127 bytes padding + 128-byte array)\n", sizeof(struct data1));
    printf("alignof(data1) = %zu\n", alignof(struct data1));
    
    printf("sizeof(data2) = %zu\n", sizeof(struct data2));
    printf("alignof(data2) = %zu\n", alignof(struct data2));
 
 
    alignas(2048) struct data1 d1;
    
    printf("sizeof(d1) = %zu\n", sizeof(d1));
    printf("alignof(d1) = %zu\n", alignof(d1));

}
 
 
 
 
/*
run:
 
sizeof(account) = 16
alignof(account) = 16
sizeof(user) = 32
alignof(user) = 16
sizeof(data1) = 256 (1 byte + 127 bytes padding + 128-byte array)
alignof(data1) = 128
sizeof(data2) = 128
alignof(data2) = 128
sizeof(d1) = 256
alignof(d1) = 2048

*/

 



answered Mar 8, 2024 by avibootz

Related questions

...