<구조체란>
- 여러개의 변수를 묶어 하나의 객체를 표현하고자 할 때 사용
- 배열과는 성질이 다름
- 배열 : 동일한 특성을 가지는 변수를 일렬로 나열
- 구조체 : 일종의 객체를 표현하고자 할때사용
- 게임에서 캐릭터, 몬스터, 학생, 좌표 등 다양한 객체를 모두 프로그래밍 언어를 이용해 표현할 수 있다.
- 구조체는 현실 세계의 객체를 소스코드 상에서 매우 쉽게 표현할 수 있도록 한다.
<구조체 선언방법>
/*
struct 구조체명{
자료형1 변수명1;
자료형2 변수명2;
...
};
*/
# include<stdio.h>
struct Student{
char studentId[10];
char name[10];
int grade;
char major[100];
}
<구조체 변수의 선언과 접근>
1) 기본적으로 구조체 변수에 접근할 때는 온점(.)을 사용한다.
struct Student s; //구조체 변수 선언
strcpy(s.srudentId,"20153157"); //구조체 변수에 접근
strpy(s.name, "고길동");
s.grade = 4;
strcpy(s.major,"컴퓨터공학과");
<구조체의 정의와 선언>
1) 하나의 구조체 변수만 사용하는 경우 정의와 동시에 선언을 할 수도 있다.
2) 이 경우 변수는 전역변수로 사용된다.
# include<stdio.h>
struct Student{
char studentId[10];
char name[10];
int grade;
char major[100];
} s
int main(void){
struct Student s; //구조체 변수 선언
strcpy(s.srudentId,"20153157"); //구조체 변수에 접근
strpy(s.name, "고길동");
s.grade = 4;
strcpy(s.major,"컴퓨터공학과");
return 0;
}
<구조체의 초기화>
1) 구조체의 변수를 한 번에 초기화하기 위해서는 중괄호에 차례대로 변수의 값을 넣는다.
# include<stdio.h>
struct Student{
char studentId[10];
char name[10];
int grade;
char major[100];
};
int main(void){
struct Student s = {'20153157','고길동',4,'컴퓨터공학과'};
printf("학번:%s\n",s,studentId);
printf("이름:%s\n",s,name);
printf("학년:%d\n",s,grade);
printf("학과:%s\n",s,major);
system("pause");
return 0;
}
<더 짧게 구조체 정의하기>
1) typeof키워드를 이용하면 임의의 자료형을 만들 수 있으므로 선언이 더 짧아진다.
# include<stdio.h>
typedef struct{
char studentId[10];
char name[10];
int grade;
char major[100];
} Student;
int main(void){
Student s = {'20153157','고길동',4,'컴퓨터공학과'};
printf("학번:%s\n",s,studentId);
printf("이름:%s\n",s,name);
printf("학년:%d\n",s,grade);
printf("학과:%s\n",s,major);
system("pause");
return 0;
}
<구조체가 포인터 변수로 사용되는 경우 내부 변수에 접근할 때 화살표(->)를 사용한다.
# include<stdio.h>
typedef struct{
char studentId[10];
char name[10];
int grade;
char major[100];
} Student;
int main(void){
Student *s = malloc(sizeof(Student));
strcpy(s->studentId,"20153157"); //구조체 포인터 변수에 접근
strcpy(s->name,"고길동");
s->grade = 4;
strcpy(s->major,"컴퓨터공학과")
printf("학번:%s\n",s->studentId);
printf("이름:%s\n",s->name);
printf("학년:%d\n",s->grade);
printf("학과:%s\n",s->major);
system("pause");
return 0;
}
'컴퓨터 기본 개념' 카테고리의 다른 글
프론트기술을 배워야 하는 이유 (0) | 2020.08.24 |
---|---|
연결리스트 (0) | 2020.08.08 |
14장. 다차원 배열과 포인터 배열 (0) | 2020.07.29 |
15강. 동적메모리할당 (0) | 2020.07.28 |
35강. 깊이 우선 탐색 (0) | 2020.07.28 |