반응형

구조체

서로 다른 형의 데이터를 한 묶음의 데이터 형태로 만듦

정수, 실수, 문자 등을 한데 모아 하나의 데이터로 취급할 수 있도록 해줌


성적처리 프로그램을 만든다고 가정할 때

이름, 국어점수, 영어점수, 수학점수, 평균, 등급은 각각

이름은 문자열

국어, 영어, 수학 점수는 int형

평균 double형

등급 문자(char형)

이런 변수형들이 사용 될 것입니다.


이걸 한 셋트로 묶습니다.

struct student{

char name[10];

int kor;

int eng;

int math;

double avg;

char grade;

};


학생들이 여러명일 때 

이렇게 묶어서 표현하면 훨씬 보기도 좋고 접근하기도 편해지겠지요?

위 구조체를 소스에 적용

#include <stdio.h>

#include <string.h>

struct student //구조체

{

char name[10];

int kor;

int eng;

int math;

double avg;

char grade;

};


int main()

{

int i;

struct student st[3]; //구조체 배열 선언

strcpy(st[0].name, "hong");//학생1

st[0].kor=95;

st[0].eng=99;

st[0].math=97;

st[0].avg=(st[0].kor+st[0].eng+st[0].math)/3;

st[0].grade='A';

strcpy(st[1].name, "leee");//학생2

st[1].kor=81;

st[1].eng=82;

st[1].math=85;

st[1].avg=(st[1].kor+st[1].eng+st[1].math)/3;

st[1].grade='B';


strcpy(st[2].name, "park");//학생3

st[2].kor=70;

st[2].eng=71;

st[2].math=75;

st[2].avg=(st[2].kor+st[2].eng+st[2].math)/3;

st[2].grade='C';



for(i=0;i<3;i++)

printf("%s %d %d %d %lf %c\n",st[i].name, st[i].kor, st[i].eng, st[i].math, st[i].avg, st[i].grade);




return 0;

}


실행 결과 



구조체를 정의 하고, 

구조체 배열을 선언 한 후

구조체 배열이름 .(도트연산자)을 누르면 구조체 변수 내의 변수형들이(구조체 멤버) 무엇인지 출력됩니다.

전 st[3]이라는 구조체 배열을 선언 하였고,

그 중 st[0]의 구조체 멤버에 접근하기위해서

st[0]. 까지 입력하면 아래와 같이 출력됩니다.



구조체를 정의 하면서 바로 구조체 배열도 선언 할 수 있습니다.

#include <stdio.h>

#include <string.h>

struct student //구조체

{

char name[10];

int kor;

int eng;

int math;

double avg;

char grade;

}st[3];


int main()

{

int i;

strcpy(st[0].name, "hong");//학생1

st[0].kor=95;

st[0].eng=99;

st[0].math=97;

st[0].avg=(st[0].kor+st[0].eng+st[0].math)/3;

st[0].grade='A';

strcpy(st[1].name, "leee");//학생2

st[1].kor=81;

st[1].eng=82;

st[1].math=85;

st[1].avg=(st[1].kor+st[1].eng+st[1].math)/3;

st[1].grade='B';


strcpy(st[2].name, "park");//학생3

st[2].kor=70;

st[2].eng=71;

st[2].math=75;

st[2].avg=(st[2].kor+st[2].eng+st[2].math)/3;

st[2].grade='C';



for(i=0;i<3;i++)

printf("%s %d %d %d %lf %c\n",st[i].name, st[i].kor, st[i].eng, st[i].math, st[i].avg, st[i].grade);




return 0;

}



메인 함수 내부의 struct student st[3]; //구조체 배열 선언

부분은 사라지고 대신 


struct student //구조체

{

char name[10];

int kor;

int eng;

int math;

double avg;

char grade;

}st[3];


이런 식으로 구조체 배열을 선언 하실 수도 있습니다.

실행결과는 동일하므로 생략.


반응형

'Computer > Programing' 카테고리의 다른 글

c언어 구조체를 함수의 인자로 넘기기  (0) 2013.12.30
c언어 문자열(2) _ 문자열 관련 함수  (0) 2013.12.26
c언어 문자열(1)  (0) 2013.12.25

+ Recent posts