프로그래밍 언어/C언어

C언어 구조체 사용하기.

원원 2017. 8. 16. 18:44

안녕하세요. 이번에는 구조체를 사용해보겠습니다.

구조체란 여러 가지 데이터를 쉽게 저장하기 위해서 사용하는 것입니다.



선언방법

 strcut 변수명{멤버 목록};


예)

1
2
3
4
5
6
struct user
{
    int HP;
    int MP;
    char job;
};
cs

user라는 변수를통해서 3가지 데이터에 접근 할 수 있습니다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<stdio.h>
 
int main()
{
    struct user
    {
        int HP;
        int MP;
        char class;
 
    };
    
    struct user user1;
    user1.HP = 100;
    user1.MP = 50;
    user1.class = 'a';
 
    printf("user1의 HP : %d \n",user1.HP);
    printf("user1의 MP : %d \n",user1.MP);
    printf("user1의 class : %c \n",user1.class);
}
cs

기본적인 구조체 사용법입니다.


구조체 쉽게 선언하기(사용자 정의 구조체)

구조체변수를 더 쉽게 선언하는 방법이 있습니다.

typedef struct {멤버 목록} 변수명;

이런식으로 선언을 한다면 구조체를 선언할때 struct를 붙이지 않아도 됩니다. 또한 typedef를 사용해야지만 구조체배열을 선언 할 수 있습니다. 그래서 대부분의 경우 구조체를 만들때 typedef를 사용합니다.


예)

1
2
3
4
5
6
typedef struct 
{
    int HP;
    int MP;
    char job;
}user;
cs




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<stdio.h>
 
int main()
{
    typedef struct 
    {
        int HP;
        int MP;
        char class;
 
    }user;
    
    user user1;
    user1.HP = 100;
    user1.MP = 50;
    user1.class = 'a';
 
    printf("user1의 HP : %d \n",user1.HP);
    printf("user1의 MP : %d \n",user1.MP);
    printf("user1의 class : %c \n",user1.class);
}
cs