C언어 문서화

(C언어)13.구조체

Mosu(정종인) 2016. 4. 27. 16:11
반응형

<구조체>


C언어에는 많은 자료형들이 있다. int라던지 double이라던지... 지금까지 이 자료형들은 묶어서 처리할 수 없었다. 하지만 지금부터는 이야기가 달라진다.


구조체. 영어로 struct 데이터를 묶어주는 역할을 한다.

배열과 다른점 : 배열은 같은 자료형의 집합, 구조체는 같거나 다른 자료형의 집합.(구조체 안에도 배열이 들어갈 수 있다.)


그럼 차근차근 절차를 밟아보자.


1. 구조체 정의하기

구조체도 나중엔 자료형처럼 사용되기 때문에 꼭 정의해주어야한다.

struct [구조체이름]{

[자료형] [변수명];

...

};


여기서 주의할 점! 구조체를 정의하는것이기 때문에 전역변수처럼 main함수 바깥에 정의해준다.


2. 구조체 선언하기

구조체를 정의했으면 선언해서 직접 써야죠! "정의 된 것을 가져와서 쓰겠다!" 라는 뜻으로 이해하면 된다.

struct [구조체이름] [구조체변수];

이것은 당연히 (메인)함수 안에 써줘야 하겠죠?


3. 구조체 사용하기

구조체를 정의하고 선언했으면 이제 사용할 수 있습니다!!

[구조체변수].[변수명]

으로 활용할 수 있다. 자세한것은 아래의 예제에서.

4-1. TIPS

구조체는 typedef를 이용해서 매우 간단하고 쉽게 정의/선언/사용 할 수 있다.

1
2
3
4
5
6
7
8
9
10
struct student{
    char name[10];
    int age;
    int grade;
};
 
int main(){
    struct student st;
    ...
}
cs

요게

1
2
3
4
5
6
7
8
9
typedef struct student{
    char name[10];
    int age;
    int grade;
}st;
 
int main(){
    ...
}
cs

요거랑 같다. 즉, typedef를 하면 밑에서 선언을 할 필요가 없어지고, 보기 쉬워지며 코드길이가 짧아진다.


4-2. TIPS

구조체의 크기는 얼마나 될까?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
#include <stdlib.h>
 
struct chongin{
    char name[10];
    int age;
    int grade;
};
 
int main(){
    struct chongin s1;
    printf("이름 : ");
    scanf("%s", s1.name);
    printf("나이 : ");
    scanf("%d", &s1.age);
    printf("학년 : ");
    scanf("%d", &s1.grade);
    printf("%s\n%d\n%d\n", s1.name, s1.age, s1.grade);
    printf("%d"sizeof(s1));
}
cs

위의 예제에서 chongin이름의 구조체의 크기를 구해보자.

char형 11

int형 4*2

다합치면 19.

근데 실행해보면 20이 나온다. 왜이럴까?

컴퓨터는 4바이트씩 쪼개서 데이터를 저장한다. 즉 구조체의 크기는 4의 배수이면서 구조체 안의 모든 변수의 크기의 합보다 작지않은 가장 가까운 수이다.



예제)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
 
struct dot_distance{
    double x1, x2;
    double y1, y2;
    double distance;
};
 
int main(){
    struct dot_distance distance;
    printf("x1 : ");
    scanf("%lf", &distance.x1);
    printf("x2 : ");
    scanf("%lf", &distance.x2);
    printf("y1 : ");
    scanf("%lf", &distance.y1);
    printf("y2 : ");
    scanf("%lf", &distance.y2);
    distance.distance=sqrt(pow((distance.x2-distance.x1),2)+pow((distance.y2-distance.y1),2));
    printf("두점 사이의 거리 : %.2lf", distance.distance);
}
cs







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>
#include <stdlib.h>
 
struct chongin{
    char name[10];
    int age;
    int grade;
};
 
int main(){
    struct chongin s1;
    printf("이름 : ");
    scanf("%s", s1.name);
    printf("나이 : ");
    scanf("%d", &s1.age);
    printf("학년 : ");
    scanf("%d", &s1.grade);
    printf("%s\n%d\n%d", s1.name, s1.age, s1.grade);
}
cs


반응형