C++ 프로그래밍/구조체

위키책, 위키책
struct tag명{
데이터형 멤버명;
데이터형 멤버명;
.
.
데이터형 멤버명;
};
struct tag명; --------- ①

struct 키워드 다음에는 tag명이 오게 되는데 tag명은 사용자 정의어이다. 이 부분은 구조체 타입에 대한 정의 부분이며 ① 처럼 선언을 해야만 변수가 선언되는 것처럼 구조체 변수가 선언되는 것이다.


구조체란 하나 이상의 원소들로 구성된 통합 자료형이다. 배열은 각 요소의 데이터형이 모두 일치하지만, 구조체의 각 원소는 자신의 자료형을 갖는데 이 형은 다른 원소의 형과 다를 수 있다. 사용자가 정의하는 데이터타입이라 할수 있다.

변수사용[+/-]

1. 구조체 변수명.멤버명
2. 구조체 포인터 변수명->멤버명.

예제[+/-]

#include<stdio.h>
#include<conio.h>
struct person{
char name[15];
int word,excel;
float avg;
};
void main(){
struct person student;
printf("이름   "); gets(student.name);
printf("워드점수   "); scanf("%d",&student.word);
printf("엑셀점수   ");scanf("%d",&student.excel);
student.avg=(student.word+student.excel)/2;
printf("이름   %s 워드   %d 엑셀 %d 평균   %.2f\n",
student.name,student.word,student.excel,student.avg);
}

예제[+/-]

#include<stdio.h>
#include<conio.h>
struct data{
char name[15];
char hakbun[15];
int kor;
int eng;
};
int grade(struct data x)
{
int z;
z=x.kor+x.eng;
return z;
}
void main(){
struct data student;
int total;
printf("이름과 학번 입력 : ");
scanf("%s %s",student.name,student.hakbun);
printf("국어 점수 영어점수 입력 : ");
scanf("%d %d",&student.kor,&student.eng);
total=grade(student);
printf("이름 : %s 학번 : %s 총점=%d\n",student.name,student.hakbun,total);
}