구조체 struct
구조체란?
* 여러 자료형을 가진 변수들을 하나의 패키지로 묶은 것
* 구조체 또한 값형이며 참조하고 싶으면 포인터를 사용하자
* 구조체라는 개념을 컴퓨터는 모른다.
사용자의 편의를 위한 개념일 뿐 내부적으로는 독립된 변수들을 사용하는 것과 같다.
장점 (사용하는 이유)
* 여러 변수들을 하나에 개념으로 묶을 수 있다. (직관성 상승)
struct personal_Information {
//인적 사항이라는 개념 아래에 묶인 변수들
char name[20];
int age;
float height;
float weight;
};
* 함수에 매개변수가 여러개일 때 실수를 줄이기 위해
(같은형이나 묵시적 변환이 가능한 자료형이 매개변수로 여러 개 들어가는 함수)
int addPerson(int id, int age, int sex, float height, float weight, float eyesight);
(위에 함수의 더 큰 문제점은 같은 자료형의 순서를 바꾸어도 컴파일러가 이를 잡아내지 못한다.)
==>> 해결책
* 매개변수를 구조체로 대신한다.
구조체 선언과 초기화
* 구조체는 내부적으로 독립된 변수들과 다를게 없다. 선언 시 초기화도 없다.
int main()
{
struct personal_Information {
char name[20];
int id;
int age;
float height;
float weight;
};
struct personal_Information my_Information;
return 0;
}
↑ 인적사항이라는 구조체를 하나 만들었다.
int main()
{
struct personal_Information {
char name[20];
int id;
int age;
float height;
float weight;
};
struct personal_Information my_Information;
strcpy(my_Information.name, "전준영");
my_Information.id = 1872004811;
my_Information.age = 20;
my_Information.height = 183.5f;
my_Information.weight = 77.4f;
return 0;
}
↑ 방법1. 변수를 일일이 대입, 초기화한다.
* 멍청해보이지만 구조체의 순서를 혼동하지 않고 안전하게 값을 넣을 수 있는 방법이다. (추천, 안전)
int main()
{
struct personal_Information {
char name[20];
int id;
int age;
float height;
float weight;
};
struct personal_Information my_Information = { "전준영", 1872004811, 20, 183.5f, 77.4f };
return 0;
}
↑ 방법2. 배열처럼 초기화한다.
* 배열처럼 가능하다는 부분에서 배열과 같이 변수 사이사이에 빈틈이 없음을 유추할 수 있다.
* 이 방법은 사실 장점2를 무시하는 방법이다. 하지만 초기화에는 유용하다. = { 0, };
typedef
* 구조체 변수 선언시 struct 구조체이름 변수이름; 형식을 지켜야 한다.
* 이를 단순화하기 위해 struct 구조체이름에 typedef을 사용한다.
typedef struct personal_Information {
char name[20];
int id;
int age;
float height;
float weight;
} personal_Information_t;
↑ 구조체 이름도 구조체 별명도 있는 선언
typedef struct {
char name[20];
int id;
int age;
float height;
float weight;
} personal_Information_t;
↑ typedef로 만든 별명만 사용할 거라면 구조체 이름을 안 만들어줘도 된다. (잘 사용함)
귀여운 그림은 쭐어님이 그리셨습니다.
'C' 카테고리의 다른 글
Byte Padding (0) | 2020.12.23 |
---|---|
구조체 배열과 포인터 (0) | 2020.12.22 |
rewind 함수, fseek 함수, ftell 함수 (0) | 2020.12.21 |
strcpy 함수와 strcat 함수 (2) | 2020.12.20 |
fgets 함수 (0) | 2020.12.20 |