구조체 (Struct)
구조체는 저희가 직접 정의하는 자료형으로써, 자바의 클래스와 조금은 비슷합니다.
구조체 안에는 여러 개의 변수가 들어올 수 있으며, 구조체를 구성하는 각 변수들을 멤버라고 합니다.
구조체를 정의하는 기본적인 형태는 다음과 같습니다.
struct 구조체이름 {
//멤버 선언
};
예를 들어서 다음과 같습니다.
struct person {
char name[20];
int age;
double height;
};
사용방법
구조체 변수를 생성하고, 구조체 멤버의 값을 사용하는 방법을 알아보겠습니다.
예시를 통해 살펴보겠습니다.
#include <stdio.h>
#include <string.h>
struct person
{
char name[20];
char * nickName;
int age;
double height;
};
int main(int argc, char const *argv[])
{
struct person a;
a.age = 23;
strcpy(a.name, "신동훈");
a.nickName = "몰?루";
printf("%s\n", a.name);
printf("%s\n", a.nickName);
return 0;
}
구조체 변수를 선언할 때에는 struct를 붙여주어야 합니다.
구조체 변수를 선언하는 부분에서 중요한 부분이 있는데,
구조체 변수는 반드시 struct 키워드를 붙여서 선언해 주어야 한다는 것입니다.
구조체의 멤버에 점근하기 위해서는 닷(.)연산자를 사용하여 접근합니다.
다음은 기본적인 구조체 사용법입니다.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct person
{
char name[20];
char * nickName;
int age;
double height;
}man1, man2;
int main(int argc, char const *argv[])
{
strcpy(man1.name, "구독");
strcpy(man2.name, "광고클릭");
struct person man3 = {"댓글", "달아주시면", 16, 160.99};
struct person mans[3] = {
{"댓글", "달아주시면", 16, 160.99},
{"완전" },
{"감사"}
};
printf("%s\n", man1.name);
printf("%s\n", man2.name);
printf("%s\n", man3.name);
printf("%s\n", mans[0].name);
printf("%s\n", mans[1].name);
printf("%s\n", mans[2].name);
return 0;
}
우선 man1, man2처럼 구조체 선언과 동시에 변수를 선언할 수 있습니다.
man3 처럼 구조체 변수 선언과 동시에 초기화할 수 있습니다.
또한 mans처럼 구조체를 배열로 사용할 수 있습니다.
아래처럼 포인터와 배열도 바로 선언 가능합니다.
struct person
{
char name[20];
char * nickName;
int age;
double height;
}* perMan, mans[3];
구조체를 가리키는 포인터
구조체를 가리키는 포인터 변수에 대해서 알아보도록 하겠습니다.
struct person * man;
위와 같이 사용하며, 포인터 역시나 struct 키워드가 필수입니다.
어떻게 사용할 수 있을까요?
struct person
{
char name[20];
char * nickName;
int age;
double height;
};
int main(int argc, char const *argv[])
{
struct person man = {"신동훈", "바보", 23, 0.1};
struct person * ptrMan = &man;
(*ptrMan).age =30;
printf("%d\n", (*ptrMan).age);
return 0;
}
위와 같이 *연산자를 통해 사용할 수 있습니다만, 이는 누가봐도 불편해 보입니다.
구조체 포인터를 조금 쉽게 사용하기 위해 C언어에서는 다음과 같은 연산자를 제공합니다.
->
이는 구조체에 대한 포인터 변수에서만 사용할 수 있으며, 다음과 같이 사용합니다.
struct person
{
char name[20];
char * nickName;
int age;
double height;
};
int main(int argc, char const *argv[])
{
struct person man = {"신동훈", "바보", 23, 0.1};
struct person * ptrMan = &man;
ptrMan -> age =30;
printf("%d\n", ptrMan -> age);
return 0;
}
구조체의 멤버인 구조체
다른 구조체의 경우 구조체의 멤버로 사용 가능합니다.
struct person
{
char name[20];
char * nickName;
int age;
double height;
};
struct school
{
char * name;
struct person students[1000];
};
int main(int argc, char const *argv[])
{
struct school school1;
school1.name = "school";
for (int i = 0; i < 1000; i++)
{
printf("%s\n", school1.students[i].age);
}
return 0;
}
다음과 같이 사용 가능합니다.
(학생들의 이름은 초기화하지 않았기에 모두 null이 나옵니다.)
같은 구조체의 경우 구조체의 멤버로 사용 불가능합니다. -> 포인터로 해결
다음 코드를 컴파일하면 에러가 발생합니다.
struct person
{
char name[20];
char * nickName;
int age;
double height;
struct person another;
};
이를 포인터를 사용하여 해결할 수 있습니다.
struct person
{
char name[20];
char * nickName;
int age;
double height;
struct person * another;
};
다음과 같이 사용합니다.
struct person
{
char name[20];
char * nickName;
int age;
double height;
struct person * another;
}man1, man2;
int main(int argc, char const *argv[])
{
man2.nickName = "광고!";
man1.another = &man2;
man1.nickName = "구독!";
man1.another->nickName = "구글광고!!!!!!";
printf("%s\n", man1.nickName);
printf("%s\n", man1.another->nickName);
return 0;
}
구조체는 함수 인자로 어떻게 전달되는가
c언어에서는 언제나 call by value입니다.
구조체는 함수 인자로 통째로 전달되고 통째로 return됩니다.
#include <stdio.h>
#include <stdlib.h>
typedef struct point {
int xpos;
int ypos;
}Point;
void ShowPosiotion (Point pos) {
printf("[%d, %d] \n", pos.xpos, pos.ypos);
}
void modifyPosition (Point p) {
printf("위치 입력해용: ");
scanf("%d %d", &p.xpos, &p.ypos);
printf("수정 후 :");
ShowPosiotion(p);
}
Point generatePostition () {
Point p;
printf("위치 입력해용: ");
scanf("%d %d", &p.xpos, &p.ypos);
return p;
}
int main() {
Point p = generatePostition();
ShowPosiotion(p);
modifyPosition(p);
ShowPosiotion(p);
}
이를 변경하기 위해서는 다음과 같이 작성합니다.
#include <stdio.h>
#include <stdlib.h>
typedef struct point {
int xpos;
int ypos;
}Point;
void ShowPosiotion (Point pos) {
printf("[%d, %d] \n", pos.xpos, pos.ypos);
}
void modifyPosition (Point * p) {
printf("위치 입력해용: ");
scanf("%d %d", &p -> xpos, &p -> ypos);
printf("수정 후 :");
ShowPosiotion(*p);
}
Point generatePostition () {
Point p;
printf("위치 입력해용: ");
scanf("%d %d", &p.xpos, &p.ypos);
return p;
}
int main() {
Point p = generatePostition();
ShowPosiotion(p);
modifyPosition(&p);
ShowPosiotion(p);
}
'c언어' 카테고리의 다른 글
[C언어] - union (0) | 2022.06.12 |
---|---|
[C언어] - typedef (0) | 2022.06.12 |
[C언어] - 동적 메모리 할당 (malloc) (0) | 2022.06.12 |
[C언어] - 이중 포인터 (0) | 2022.05.06 |
[C언어] - 다차원 배열 (0) | 2022.05.06 |