Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

What's the difference between sizeof and alignof?

#include <iostream>

#define SIZEOF_ALIGNOF(T) std::cout<< sizeof(T) << '/' << alignof(T) << std::endl

int main(int, char**)
{
        SIZEOF_ALIGNOF(unsigned char);
        SIZEOF_ALIGNOF(char);
        SIZEOF_ALIGNOF(unsigned short int);
        SIZEOF_ALIGNOF(short int);
        SIZEOF_ALIGNOF(unsigned int);
        SIZEOF_ALIGNOF(int);
        SIZEOF_ALIGNOF(float);
        SIZEOF_ALIGNOF(unsigned long int);
        SIZEOF_ALIGNOF(long int);
        SIZEOF_ALIGNOF(unsigned long long int);
        SIZEOF_ALIGNOF(long long int);
        SIZEOF_ALIGNOF(double);
}

will output

1/1 1/1 2/2 2/2 4/4 4/4 4/4 4/4 4/4 8/8 8/8 8/8

I think I don't get what the alignment is...?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
373 views
Welcome To Ask or Share your Answers For Others

1 Answer

Well, "memory" is basically a huge array of bytes. However, most larger things like integers need more than 1 byte to store them -- a 32 bit value, for example, would use 4 consecutive bytes of memory.

Now, the memory modules in your computer aren't usually "bytes"; they are also organized with a few bytes "in parallel", like blocks of 4 bytes.

For a CPU, it's much easier = more efficient = better performance to not "cross" such block-borders when reading something like an integer:

memory byte    0 1 2 3     4 5 6 7       8 9 10 11
 integer       goooood
                   baaaaaaaaad

This is what the "alignment" says: an alignment of 4 means that data of this type should (or must, depends on the CPU) be stored starting at an address that is a multiple of 4.

You observation that sizeof==alignof is incorrect; try structures. Structures will also be aligned (because their individual members need to end up on the correct addresses), but their size will be much larger.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...