Struct 구조체 메모리 할당 크기

2024. 7. 10. 21:02정보처리,전산/Clang

반응형
#include <math.h>
#include <stdio.h>
#include <string.h>


struct student{
 int age;
double score;
int grade;
};

//자료형의 제일 큰 할당 크기로 double 8byte로 할당됨


int main(void){
  struct student form;
  printf("%d",sizeof(struct student));
  printf("%d",sizeof(form));
  return 0;
}

 




   - struct student 구조체는 세 개의 멤버를 가지고 있다:
     - int age: 4 bytes
     - double score: 8 bytes
     - int grade: 4 bytes


구조체의 크기를 계산할 때 메모리 정렬 (Padding)을 최적화하기 위해 추가적인 패딩을 삽입할 수 있다. 각 멤버의 크기와 메모리 정렬 요구 사항에 따라 구조체의 최종 크기가 결정된다.

- int 타입은 4 bytes, 정렬 요구 사항은 4 bytes이다.
- double 타입은 8 bytes, 정렬 요구 사항은 8 bytes이다.

 

 


구조체의 메모리 배치

struct student {
    int age;        // 4 bytes
    char padding1[4]; // 4 bytes (패딩)
    double score;   // 8 bytes
    int grade;      // 4 bytes
    char padding2[4]; // 4 bytes (패딩)
}


최종 구조체 크기는 4 + 4 (패딩) + 8 + 4 + 4 (패딩) = 24 bytes가 된다.

 

반응형

'정보처리,전산 > Clang' 카테고리의 다른 글

구조체 값 입력 받기  (0) 2024.07.18
포인터, 문자열, 배열, 기본 입출력  (0) 2024.07.15
2진수를 10진수 16진수로 출력  (0) 2024.07.06
포인터 변수 **p  (0) 2024.07.06
지역변수 정적변수  (0) 2024.07.04