C

[내배캠자습]C언어 챕터 9-1 : 구조체

BreadMushroom 2026. 3. 29. 17:31

지금까지 사용한 자료형은 모두 Built-In type.

언어에 내장된 기본 자료형. ex) char, int, … 근데 나만의 자료형이 필요하다면 어떻게 해야 될까요?

ex) 주민등록번호(int), 이름(char[])을 모아놓고 Human 자료형을 만들고 싶습니다. 그리고 Human Classmate[30];을 원합니다. 지금까지 배운 내용이라면, 굳이 주민등록번호용 int 변수 30개 이름용 문자배열 30개를 따로 선언해서 써야합니다.

구조체(Structure)

필요한 여러 자료형의 변수들을 한데 묶어서 하나의 자료형처럼 만들 수 있습니다.

아래와 같은 코드로 정의 가능합니다. 예제 코드를 반복적으로 클론 코딩 해보며 숙지해봅시다.

struct 구조체명 
{
	자료형 변수명;
	...
};

 

Ex090101) 구조체 정의

아래 소스코드를 따라서 작성해봅시다.

// Main.c

struct Date
{
	int Year;
	int Month;
	int Day;
};

int main(void)
{

	return 0;
}

Ex090102) 구조체 변수 선언

아래 소스코드를 따라서 작성해봅시다.

// Main.c

struct Date
{
	int Year;
	int Month;
	int Day;
};

int main(void)
{
	struct Date Birthday; // 사용자 정의 자료형 Date 변수 선언.

	return 0;
}

Ex090103) 구조체 멤버 접근 연산자

. 연산자를 구조체 멤버 접근 연산자라고 합니다. 아래 소스코드를 따라서 작성해봅시다.

// Main.c

#include <stdio.h>

struct Date
{
	int Year;  // 구조체 Date의 멤버 Year.
	int Month; // 구조체 Date의 멤버 Month.
	int Day;   // 구조체 Date의 멤버 Day.
};

int main(void)
{
	struct Date Birthday;
	Birthday.Year = 2024;
	Birthday.Month = 1;
	Birthday.Day = 13;

	printf("%d/%d/%d\\n", Birthday.Year, Birthday.Month, Birthday.Day);

	return 0;
}

Ex090104) 함수의 인자로 구조체 변수 전달 [중요 샘플 코드]

아래 소스코드를 따라서 작성해봅시다.

// Main.c

#include <stdio.h>

struct Date
{
	int Year;
	int Month;
	int Day;
};

void PrintBirthday(struct Date InBirthday);

int main(void)
{
	struct Date Birthday;
	Birthday.Year = 2024;
	Birthday.Month = 1;
	Birthday.Day = 13;
		// 구조체 변수 Birthday는 어느 메모리에 저장 될까요?.
		// 당연하게도 스택 메모리입니다. 다른 기본 자료형과 마찬가지입니다.
		// 초기화 하지 않으면 0이 아닌 쓰레기 값이 저장되어 있습니다.

	PrintBirthday(Birthday);

	return 0;
}

void PrintBirthday(struct Date InBirthday)
{
	printf("%d/%d/%d\\n", InBirthday.Year, InBirthday.Month, InBirthday.Day);
}

// Main.c

#include <stdio.h>

struct Stats
{
	int HP;
	int Stamina;
	int Speed;
	
};

void PrintStats(struct Stats list)
{
	if (list.Stamina <= 10)
	{
		printf("체력이 부족하여 달릴 수 없습니다.\n");
		return;
	}
	printf("HP:%d , Stamina:%d , Speed:%d", list.HP, list.Stamina, list.Speed);
}

int main(void)
{
	struct Stats Cham;
	Cham.HP =2000;
	Cham.Stamina = 100;
	Cham.Speed = 50;
	

	PrintStats(Cham);

	return 0;
}

Ex090105) 문제의 코드

아래 소스코드를 따라서 작성해봅시다. 문제가 될만한 부분이 어딘지 고민해보고 실행해봅시다.

// Main.c

#include <stdio.h>

struct Date
{
	int Year;
	int Month;
	int Day;
};

void PrintBirthday(struct Date InBirthday);

int main(void)
{
	struct Date Birthday;

	PrintBirthday(Birthday);

	return 0;
}

void PrintBirthday(struct Date InBirthday)
{
	printf("%d/%d/%d\\n", InBirthday.Year, InBirthday.Month, InBirthday.Day);
}

초기화 되지 않은 구조체의 변수를 사용하려고 했기 때문에 오류가 발생했다.

초기화 하지않으면 변수에 쓰레기값이 들어있기 때문에 꼭 사용전에 초기화를 해주어야 된다.