1. sizeof basic types
sizeof 함수는 크기를 나타내므로 양수. --> unsigned 사용!
sizeof 함수를 나타내는 방법은 다음과 같이 3가지가 있다.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{
int a = 0;
unsigned int int_size1 = sizeof a; // 1. 선언된 변수 이름 넣기
unsigned int int_size2 = sizeof(int); // 2. 자료형 직접 입력. 괄호 필수! int는 연산자!
unsigned int int_size3 = sizeof(a); // 3. 괄호 안에 변수 이름 넣기
size_t 가 하는 일은 위의 unsigned int와 동일하다. 하지만, 다른 시스템에서 sizeof의 범위를 나타내기 위해 unsigned int를 사용하지 않았을 수 있다.
즉, 이식성을 높이기 위해서 size_t 를 사용하는 것이다.
size_t int_size4 = sizeof(a);
size_t float_size = sizeof(float);
printf("Size of int type is %u bytes.\n", int_size1); // unsigned 에 대한 type specifier = u
printf("Size of int type is %zu bytes.\n", int_size4); // size_t 에 대한 type specifier = zu
printf("Size of int type is %zu bytes.\n", float_size);
}
2. sizeof arrays
동적 할당. 어려운 내용이고 나중에 더 설명하실 것 같다.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{
int int_arr[30]; // int_arr[0] = 1024; ...
int *int_ptr = NULL;
int_ptr = (int*)malloc(sizeof(int) * 30); //int_ptr[0] = 1024; ...
// int_ptr 은 할당된 메모리 중 대표 주소를 찍어주는 것이다.
printf("Size of array = %zu bytes\n", sizeof(int_arr)); // 30 개의 공간이므로 120 byte
printf("Size of pointer = %zu bytes\n", sizeof(int_ptr)); // 120 byte를 대표 주소 --> 4 byte
}
3. sizeof character array
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main()
{
char c = 'a'; // 정수 97 로 바뀌어 저장.
char string[10]; // maximally 9 character '\0' (null character)
//string은 마지막에 마침표 역할을 하는 null character 필수! --> 실질적으로 9자리 밖에 저장이 안 된다.
size_t char_size = sizeof(char);
size_t str_size = sizeof(string);
printf("Size of char type is %zu bytes.\n", char_size); // 1
printf("Size of char type is %zu bytes.\n", str_size); // 10
}
4. sizeof structure
구조체는 추후 설명 예정
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h> // malloc() -> memory allocation. 메모리 할당.
struct Mystruct // 구조체
{
int i;
float f;
};
int main()
{
printf("%zu\n", sizeof(struct Mystruct)); // 8 = 4(int) + 4(float)
return 0;
}