프로그래밍/C언어

[C언어]typedef와 구조체

FORHAPPy 2021. 9. 5. 02:27

<1> typedef

int main() { typedef int int32; }
typedef 는 기존의자료형(int) 에다가 별명 (int32)을 붙여주는것이다. int와 int32랑은 같은의미를 말한다.


- 예시 -

typedef int pair[2];   
pair point = { 3,4 };  
pair은 2개짜리 인트형 배열을 의미한다.
int point[2] = { 3,4 }와 같은 의미이다. 

<2> typedef를 사용하여 문자열 담기 

 

<typedef 없이 문자열 담는 방법>

char* name = "hello";

char name[] = "hello";


<typedef 사용하여 문자열 담는 방법>

typedef char* String;
String name = "hello";

char형 포인터에 새로운 이름(String)을 만들어 준다. 즉, 자료형에 특별한 의미가 부여될떄 typedef를 쓴다.

 

<3>구조체

 

typedef int Pair[2];
Pair p;                

p[0] = 3;             
p[1] = 4;             

 x좌표 y좌표인걸 알아차리기 어렵다. 직관적이지가 앉다.
이것을 구현하는 방법이 strucr 구조체 이다. 
즉, 여러개(int x, int y)의 변수를 하나(Point)로 묶은것이다.


typedef struct { int x, y; } Point; 

Point p;                               


p.x = 3;                                
p.y = 4;                                

 

1. typedef struct { int x, y; } Point; 이부분은 메모리를 차지 하지 않음

2. Point p; 의 구조체 p는 2개의 공간 총 8바이트의 메모리 공간을 차지한다.

3. typedef struct { int x, y; } Point; 에서 struct { int x, y; } = Point 와 완전히 대체해서 쓸 수 있다.

4. typedef를 생략하고 struct Point { int x, y; }; 이런식으로 쓸 수 있다.

5. 구조체는 주로 전역변수로 많이 쓰인다.

6. struct Point { int x, y; }; 안에 형이 다른 변수를 여러번 선언해도 된다.

7. Point p = { 3, 4 }; 이렇게 중괄호 형태로 초기화도 같이 할 수 있다.                                                           

   (등호 생략 가능)  ( p.x = 3 p.y = 4; 이렇게 따로 적을 필요 없다.)

 

<4>구조체를 가르키는 포인터

 

struct ProductInfo { 
      int num;          
      char name[100];
      int cost; };        


int main() {                                                                   
       ProductInfo myProduct{ 4797283, "제주 한라봉", 19900 }; 
       ProductInfo* ptr_product = &myProduct ;                     
        (자료형을 먼저 적고, 별> 포인터의 이름)


<아래는 3가지 경우 모두 4797283, 제주 한라봉이 출력된다.>


printf("상품번호 : %d\n", ptr_product->num);
printf("상품이름 : %s\n", ptr_product->name);

 

printf("상품번호 : %d\n", (*ptr_product).num);
printf("상품이름 : %s\n", (*ptr_product).name);

printf("상품번호 : %d\n", myProduct.num);
printf("상품이름 : %s\n", myProduct.name);

 

<가격의 10%를 할인하는 함수를 만들고 싶을때 아래와 같다.>

 

void productSale(ProductInfo *p, int percent) {
(*p).cost -= (*p).cost * percent / 100;             
p->cost -= p->cost * percent / 100;}             

 


<5>구조체 안에 함수를 넣을때

 

struct Time {                                                  
      int h, m, s;                                               
      int totalSec() { return 3600 * h + 60 * m + s; }}
int main() {                                                    
      Time t = { 1, 22, 48 };                                 
      printf("%d\n", t.totalSec());                          

 

구조체 안에 넣었기 때문에 구조체를 매개변수로 안써도 된다.

totalSec() 도 구조체 범위 안에 있기 때문에 t.h, t.m 이런 형태로 쓰지 않아도 된다. 


<참고1>

struct Point{
          int x, y;
          void moveRight(){ x++; }
          void moveLeft() { x--; }
          void moveUp() { y++; }
          void moveDown() { y--; }
};
int main() {
         Point p = { 2, 5 };
         p.moveDown();
         p.moveRight();
         printf("(%d, %d)\n", p.x, p.y);

 

<참고2>

struct Point {
     int x, y;
     void  pSwap() {
             int temp = x;
             x = y;
             y = temp; };};
int main() {
       Point pos = { 3, 4 };

       pos.pSwap();
       printf("(%d, %d)\n", pos.x, pos.y);}

 

<참고3>

struct Point {
         int x, y;};
void  pSwap(int *p) {
      int temp = p->x;
      p->x = p->y;
      p->y = temp;};
int main() {
       Point pos = { 3, 4 };
       pSwap(&pos);
       printf("(%d, %d)\n", pos.x, pos.y);}