관련 있는 데이터를 묶어서 하나의 자료형으로 그룹화하면 관리가 쉽고 코드의 가독성과 간결성이 한결 높아지는 장점을 지님
struct point // 구조체 키워드/구조체 이름
{
int x; // 구조체 멤버변수
int y;
};
struct point
{
int x;
int y;
} p1, p2, p3; // 구조체 변수들
#include <stdio.h>
struct point
{
int x;
int y;
};
int main(void)
{
struct point p1, p2, p3; // 구조체 변수를 개별적으로 선언
...
return 0;
}
#include <stdio.h>
struct group
{
int a;
double b;
};
int main(void)
{
struct group g1;
g1.a = 10;
g1.b = 1.234;
printf("g1.a의 값: %d \n", g1.a);
printf("g1.b의 값: %lf \n", g1.b);
return 0;
}
g1.a;
구조체 변수/접근 연산자(.)/멤버 변수
ex)
#include <stdio.h>
struct point
{
int x;
int y;
};
int main(void)
{
struct point p1 = {10, 20}; // 구조체 변수의 초기화
pritnf("%d %d \n", p1.x, p1.y);
return 0;
}
struct point p1;
p1={10, 20}; // error
ex)
#include <stdio.h>
struct score
{
double math;
double english;
double total;
};
struct student
{
int no;
struct score s;
};
int main(void)
{
struct student stu = {20101323, {90, 80, 0}};
// struct student stu = {20101323, 90, 80, 0}; // 중괄호 생략해도 데이터는 순서대로 저장됨
stu.s.total = stu.s.math + stu.s.english;
printf("class of %d \n", stu.no);
printf("total score %lf \n", stu.s.total);
return 0;
}
typedef struct score
{
...
} SCORE;
/// 일반화
typedef struct 구조체 이름
{
...
} 새 구조체 이름
struct score
{
...
};
typedef struct score SCORE;
/// 일반화
struct 구조체 이름
{
...
}
typedef struct 구조체 이름 새로운 구조체 이름;
ex) point 이름의 구조체에 멤버 변수로 포인터를 사용
struct point
{
int* x; // 멤버 변수로 1차원 포인터 선언
int** y; // 멤버 변수로 다차원 포인터 선언
};
#include <stdio.h>
struct student
{
char no[10];
char name[20];
double total;
};
int main(void)
{
struct student stu = {"20101323", "Park", 160};
struct student *p = NULL; // 구조체 변수로 1차원 포인터 선언
p = &stu; // struct student의 주소를 저장
printf("%s %s %lf \n", stu.no, stu.name, stu.total);
printf("%s %s %lf \n", (*p).no, (*p).name, (*p).total); // 1차원 포인터를 이용한 접근, *p == *&stu == stu
printf("%s %s %lf \n", p->no, p->name, p->total); // 1차원 포인터를 이용한 접근, -> 연산자는 포인터 변수에만 사용. -> 연산자는 포인터 변수만으로 구조체의 멤버 변수에 접근 가능, 위 보다 더 많이 사용
return 0;
}
struct developer
{
char name[20];
int age;
struct developer* p;
};
struct developer
{
char name[20];
int age;
struct language* p;
};
void function(struct point a)
{
...
}
void function(struct point* a)
{
...
}
struct point function()
{
struct point p = {10, 20};
return p;
}
struct point* function()
{
static struct point p = {10, 20};
return &p;
}
ex)
union date
{
int i;
char c;
double d;
}
enum week {ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN};
열거형 키워드/ 열거형 이름 / {상수 이름}
Reference
강의: 박정민, 『C 프로그래밍』, KOCW 한국산업기술대학교, 15강
교재: 박정민, 『열혈강의 C 언어 본색 명강의가 일으키는 C 언어 기적』, 프리렉 (2011), p472-531.