C/C++ 언어 구조체 변수의 인자 전달 이해를 위한 예제 프로그램


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/* 구조체 변수의 인자 전달 이해를 위한 예제 프로그램 */
 
#include <stdio.h>
 
 
typedef struct {
  char name[20];
  int kor, eng, total;
} ST;
 
int sum1(intint);
void sum2(intintint *);
void sum3(ST *pup);
void sum4(ST st4);
void sum5(ST *st5); 
 
void main(void) {
  int i;
  ST st1={"박문수"89910};
  ST st2={"홍길동"87920};
  ST st3[3]={
    {"이순신"97930},
    {"김유신"94890},
    {"최영",   95910}};
  ST st4={"임꺽정"85790};
  ST st5={"허준"98950};
 
  printf(" name  kor eng total\n");
  printf("===================\n");
  st1.total = sum1(st1.kor, st1.eng);
  /* 구조체 멤버 전달 */
  printf("%6s %3d %3d %3d\n",
    st1.name, st1.kor, st1.eng, 
    st1.total);
 
  sum2(st2.kor, st2.eng, &st2.total);
  /* 구조체 멤버 및 멤버 주소 전달 */
  printf("%6s %3d %3d %3d\n",
    st2.name, st2.kor, st2.eng, 
    st2.total);
 
  sum3(st3);    /* 배열 이름 전달 */
  for (i=0; i<3; i++)
    printf("%6s %3d %3d %3d\n",
    st3[i].name, st3[i].kor,
    st3[i].eng, st3[i].total);
  sum4(st4);    /* 구조체 자체 전달 */
  printf("%6s %3d %3d %3d\n",
    st4.name, st4.kor, st4.eng,
    st4.total);
 
  sum5(&st5);  /* 구조체 번지 전달 */
  printf("%6s %3d %3d %3d\n",
    st5.name, st5.kor, st5.eng,
    st5.total);
/* end main */
 
int sum1(int x, int y) {
  return (x + y);
}
 
void sum2(int x, int y, int *z) {
  *= x + y;
}
 
void sum3(ST *pup) {
  int i;
 
  /* pup++는 다음 구조체로 포인터 이동 */
  for (i=0; i<3; i++, pup++)
    pup->total = pup->kor + pup->eng;
}
 
void sum4(ST st4) {
  st4.total = st4.kor + st4.eng;
}
 
void sum5(ST *st5) {
  st5->total = st5->kor + st5->eng;
}
 
cs


C/C++ 언어 구조체 변수의 인자 전달 이해를 위한 예제 프로그램



+ Recent posts