달력

5

« 2024/5 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

1.구조체를 선언할 때 typedef 사용

구조체 변수를 선언 할 때에는 다음과 같이 한다.

struct      자료형_이름      변수_이름;

일반적인 자료형인 int나 double과 마찬가지로 [자료형_이름     변수_이름;] 이렇게 선언하고 싶을 것이다.

앞에있는 struct를 떼버리고...

그런데 typedef 선언을 이용하면 이것이 실제로 가능하다.

typedef    struct    자료형_이름    새롭게_축약된_자료형_이름;        

이 선언에 의해서 새롭게_축약된_자료형_이름 이 struct    자료형_이름 을 대신 할 수 있는 것이다.

이 후 변수를 선언할 때, 컴파일러에 의하여 struct    자료형_이름 새롭게_축약된_자료형_이름이 둘 다 사용될 수 있다. 


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>
 
struct point
{
    double    xpos;
    double    ypos;
};
 
typedef    struct point point;
 
int main(void)
{
    point p1;
    struct point p2;
 
    p1.xpos = 0.1, p1.ypos = 0.2;
    p2.xpos = 2.4, p2.ypos = 2.5;
 
    printf("X축 거리: %g \n", p2.xpos - p1.xpos);
    printf("Y축 거리: %g \n", p2.ypos - p1.ypos);
 
    while (1);
}
cs



2.구조체의 정의에 포험되는 typedef

위의 코드에서는 구조체의 정의와 typedef선언을 별도로 하고 있다.

하지만 이 둘을 다음과 같이 묶어서 선언할 수 있다.

 struct   point

{

   double xpos;

   double ypos;

};

typedef   struct point point;

 typedef  struct  point

{

    double  xpos;

    double  ypos;

}  point;


아래의 코드는 위의 코드를 오른편에 선언방식으로 대체한 것이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>
 
typedef struct point
{
    double    xpos;
    double    ypos;
}point;
 
int main(void)
{
    point p1;
    struct point p2;
 
    p1.xpos = 0.1, p1.ypos = 0.2;
    p2.xpos = 2.4, p2.ypos = 2.5;
 
    printf("X축 거리: %g \n", p2.xpos - p1.xpos);
    printf("Y축 거리: %g \n", p2.ypos - p1.ypos);
 
    while (1);
}
cs


:
Posted by youjin.A