Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,026 questions

51,982 answers

573 users

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

2 answers 274 views
1 answer 122 views
2 answers 132 views
1 answer 144 views
144 views asked May 16, 2022 by avibootz
1 answer 178 views
...