본문 바로가기
c

11_구조체(structure)

by RongBee 2023. 4. 5.

Structure는 구조라는 뜻이고, c언어에서 structure는 기본 자료형을 조합하여

 

사용자가 정의하는 자료형으로 만들어 사용하는 것을 의미한다.

 

사용자 정의 자료형이라고 하며, 구조체를 선언할 때 struct키워드를 사용하여 선언한다.

 

 

struct Monster
{
   char Normal;
   int Rare;
   short Hero;
   long long Legend;
}

 

 

구조체를 선언함으로써 char형 공간과 int, short, long long의 공간을 모두 쓸 수 있게 되었다.

 

 

long long
8byte
Legend
(멤버)
int
4byte
Rare
(멤버)
short
2byte
Hero
(멤버)
char
1byte
Normal(멤버)

 

 

이러한 구조체의 공간을 이루고 있는 기본 자료형들을 멤버라고 하며, 그 공간에 대한 이름을 가지고 있어야 한다.

 

 

struct Monster Mococo; // 구조체 변수 선언

Mococo.Red = 10;
Mococo.Blue = 100;
Mococo.Green = 1000;

 

 

구조체 변수 선언은 이렇게 해준다. 그리고 구조체를 이루고 있는 특정 멤버에 직접 접근하는 연산자는( . )이다.

 

그래서 Mococo라는 구조체 변수가 선언된 후 Mococo 구조체를 이루고 있는 멤버에 접근하기 위해 . 을 써 준 것이다.

 

그리고 자료형에 대한 프로그래머의 별칭을 지정해주는 typedef키워가 있다.

 

 

typedef unsigned int UINT; 
typedef int INT;
typedef char UCHAR;
typedef long long ULONG;
typedef short USHORT;

typedef struct tag_Monster
{
   UCHAR Code;
   INT Level;
   signed Hp;
   unsigned Atk;
}Monster; // 별칭

int main()
{ 
   //case 1
   Monster RedMococo; // Monster라는 구조체의 설계도로 지어진 RedMococo라는 메모리 공간을 생성

   RedMococo.Code  = 1;
   RedMococo.Level = 1;
   RedMococo.Hp    = 50;
   RedMococo.Atk   = 10;
   
   // case 2     이런식으로 한번에 초기화가 가능하고 구조체 멤버 순서대로 값이 초기화 된다.
   Monster Slime = { 2, 3, 80, 13};

   Monster Copy;     // Monster라는 구조체의 설계도로 지어진 Copy라는 메모리 공간을 생성

 

 

이런식으로 정의하여 사용할 수 있다.

 

그리고 typedef을 통해 구조체 변수를 정의 하여 사용해보자

 

 

typedef unsigned char       UCHAR;
typedef unsigned short      USHORT;
typedef unsigned int        UINT;
typedef unsigned long long  ULONG;

typedef struct tag_OneRoom
{
    UINT  BedRoom;
    UCHAR BathRoom;
}OneRoom;

struct tag_Apart
{
   ULONG   LivingRoom;
   UCHAR   KitChen;
   OneRoom BedAndBathRoom;
}

typedef struct tag_Apart Apart;

int main()
{
   Apart apart;

   apart.LivingRoom     = 8;
   apart.Kitchen        = 2;

   apart.BedAndBathRoom.BathRoom = 1;
   apart.BedAndBathRoom.BedRoom  = 4;

   return 0;
}

 

'c' 카테고리의 다른 글

13_문자열(string)  (0) 2023.04.11
12_배열(Array)  (0) 2023.04.08
10_반복문2(for)  (0) 2023.04.02
09_반복문1(while, do while)  (0) 2023.03.30
08_조건문2(switch, case)  (0) 2023.03.27

댓글