[열혈C프로그래밍] chapter 20. 구조체와 사용자 정의 자료형2

chapter 20

구조체와 사용자 정의 자료형2

typedef

## include <stdio.h>

typedef char* string; //자료형 char * 을 string으로 새이름을 부여하였다. 이로써 char* 와 string은 차이가 없다.

int main(void){

  string str = "hello";

  printf("%s \n", str);

  return 0;
}

구조체의 정의와 typedef 선언

typedef struct point Point; // 자료형 struct point에 Point라는 이름을 부여.

or

typedef struct point 
{
	int xpos;
	int ypos;
}Point; // 자료형 struct point에 Point라는 이름을 부여.

=> 이로써 struct point pos;라고 구조체 변수를 선언하지 않아도 되고, Point pos;라고 구조체 변수를 선언할수 있다.

구조체의 이름 생략
=>아래의 예시와 같이 생략할 수 있다.


typedef struct
{
	char* name;
  char* phoneNum;
  int age;
}Person;

struct person man; // 불가능한 선언 (이름을 생략했으니깐)
Peson man; //가능한 선언.

함수로의 구조체 변수 전달과 반환

함수의 인자(Argument)로 구조체 변수가 전달될 수 있으며,
이러한 인자를 전달 받을수 있도록 구조체 변수가 매개변수(Parameter)의 선언으로 올수 있다.
그리고 구조체 변수를 보낼 때 call by value, call by reference 모두 할 수 있다.
그리고 구조체 변수는 반환형으로서 역할도 할 수 있다.

## include <stdio.h>

typedef struct{
  int xpos;
  int ypos;

}Point;

Point getPoint(Point pos){
  
  printf("현재 좌표를 입력하세요.\n");
  scanf("%d %d", &pos.xpos, &pos.ypos);

  return pos;
}

void showPoint(Point pos){

  printf("현재 좌표는 <%d,%d>입니다. \n", pos.xpos, pos.ypos);
}

int main(void){

  Point pox;

  pox = getPoint(pox);
  
  showPoint(pox);

  return 0;
}

중첩된 구조체

## include <stdio.h>

typedef struct{
  int xpos; 
  int ypos;
}Point;

typedef struct{
  Point cen;
  double rad;

}Circle;

int main(void){
  
  Point current = {10,20};
  Circle cir = { current , 4.5};
  printf("현재 위치: %d %d \n", cir.cen.xpos, cir.cen.ypos);
  printf("반지름: %f \n", cir.rad);


  return 0;
}

Union type (공용체)

typedef struct ubox // 공용체 sbox의 정의 { int mem1; int mem2; double mem3; }

=> 다만, 메모리에서의 할당방식이 차이가 있다.<br>
구조체 변수는 구조체의 멤버들을 메모리에  각각 할당하지만, 반면 union 변수가 선언되면 <br>
공용체를 구성하는 멤버는 각각 할당하지 않고, 그 중 크기가 가장 큰 멤버의 변수만 할당되어 이를 공유한다.<br>

union의 멤버 중 가장 큰 멤버의 크기로 메모리가 할당되고 이를 모든 멤버가 공유한다.<br>
또, 멤버중 정수형 변수가 할당되면 실수형 변수의 값은 0.0이 되고,<br> 
실수형 변수가 할당되면 정수형 변수의 값은 0이 된다. <br>

### Enumerated type (열거형)

* 열거형 변수는 저장이 가능한 값 자체를 정수의 형태로 결정하고, 이 값들을 열거하여 열거형(enumerated type)이라 한다.
```c
enum syllable
{
  Do=1,Re=2,Mi=3,Fa=4,So=5,La=6,Ti=7
};