7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C言語 構造体アライメントの入り方

Posted at

##環境

今回検証したPC
64bit Mac
               ↓補足

サイズ(64bit) サイズ(32bit)
char 1byte 1byte
short 2byte 2byte
int 4byte 4byte
float 4byte 4byte
long 8byte 4byte
double 8byte 8byte

※OSによって上記とは異なる場合があります。

##おさらい

構造体のデータサイズは単純にメンバの合計サイズにならないことがある。
例1)バイト境界が1byteのためパディングがなく
メンバの合計サイズ=構造体のサイズ

example1
typedef struct
{
     char a;
     char b;
}EXAMPLE;

例2)バイト境界が4byteのためcharとintの間に3byte分のパディングがあるそのため
メンバの合計サイズ≠構造体のサイズ

example2
typedef struct
{
     char a;
     int b;
}EXAMPLE;

#本題

上記を踏まえた上で構造体の中に構造体が入ってる場合、
バイト境界は構造体単位になるのかその構造体のメンバ単位になるのか気になったのでやってみた

sample1.c
#include <stdio.h>

typedef struct
{
    char year[2];
    char month[2];
    char day[2];
}TIME;

typedef struct
{
    long a;
    TIME time;
    char b;
}KOZOTAI;

int main()
{
    KOZOTAI kou;
    printf("構造体のサイズは%luバイト\n", sizeof(kou));
    
    return 0;
}   
output:構造体のサイズは16バイト
sample2.c
 #include <stdio.h>
 
 typedef struct
 {
     char year[2];
     char month[2];
     char day[2];
     char dmy;
 }TIME;
 
 typedef struct
 {
     TIME time;
     short a;
 }KOZOTAI;
 
 int main()
 {
     KOZOTAI kou;
     printf("構造体のサイズは%luバイト\n", sizeof(kou));
     
     return 0;
 }   
output:構造体のサイズは10バイト
sample3.c
 #include <stdio.h>
 
 typedef struct
 {
     char year[2];
     char month[2];
     char day[2];
 }TIME;
 
 typedef struct
 {
     TIME time;
     int a;
 }KOZOTAI;
 
 int main()
 {
     KOZOTAI kou;
     printf("構造体のサイズは%luバイト\n", sizeof(kou));
     
     return 0;
 }   

output:構造体のサイズは12バイト

###まとめ
・構造体がメンバにいても基本的には通常の型だけの場合と大して変わらないようであった
・構造体のメンバの最大バイト長に合わせて全てのメンバにパディングが入るわけではなかった

7
6
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?