Contents

Develop
2003.04.23 10:57

[c] 구조체의 설명과 예제..

조회 수 8400 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
구조체 : 서로 관련있으면서 다른 이름과 데이타 타입을 갖는 요소들을 모아놓은 것.
다른 프로그래밍 언어에서는 레코드라고도 한다.

구조체의 장점
1. 서로 연관된 데이터들을 묶어서 하나의 단위로 취급할 수 있다. 
2. 구조체 대입 (structure assignment) 이 가능하다.
3. 함수의 parameter 로서 구조체를 통째로 건네줄 수도 있고, 함수의 리턴값으로 구조체를 통째로
     리턴받을 수도 있다.

구조체의 예
다음 문장은 
        struct complex {
            double  real;
            double  imag;
        };
        struct complex  x, y;

아래와 같은 의미이다.

        struct complex {
            double  real;
            double  imag;
        } x, y;


다음은 잘못된 구조체 선언이다.
        struct  S {
           int  a;
           struct  S  next;
        };

다음은 올바른 구조체 선언이다.
        struct  S {
            int  a;
            struct  S  *next;
        };

관련 연산자
멤버 연산자('.')
구조체 안에는 여러 개의 멤버가 있을 수 있다. 그리고, 그 멤버의 종류는 C 의 자료형이면
어느 것이든지 상관없다. 그리고 그러한 멤버들을 참조할 수 있도록 해 주는 연산자가 바로
멤버 연산자이다. 만일 name 이 구조체명이고 member 는 구조 템플릿에 기술된 멤버라면, 

            name.member 

는 구조체의 멤버를 나타낸다. 멤버 연산자는 나중에 배울 유니언에 대해서도 같은 방식으로
사용된다. 다음의 예는 구조체 item 의 멤버 code 에 값을 대입하는 것이다. 

              struct {
                  int code;
                  float cost;
              } item;

              item.code = 1212;


간접 멤버 연산자('->')
이 연산자는 구조체나 유니언의 구성원을 식별하기 위해서 구조체나 유니언에 대한
포인터와 함께 사용된다. ptrstr 이 구조체에 대한 포인터이고, member 가 구조체 템플릿에
기술된 멤버라면, 

            ptrstr->member 

는 포인터가 가리키는 구조체의 구성원임을 나타낸다. 간접 구성원 연산자는 유니언에
대해서도 같은 방식으로 사용된다. 

              struct {
                  int code;
                  float cost;
              } item, *ptrstr;

              ptrstr = &item;
              ptrstr->code = 3434;

이것은 구조체 item 의 구성원 code 에 값을 대입한다. 다음 세 연산식은 모두 동일하다. 
           ptrstr->code      item.code       (*ptrstr).code

예제: simplestruct.c
     1  #include <stdio.h>
     2
     3  struct complex {
     4      int  real;
     5      int  imag;
     6  };
     7
     8  main() {
     9      struct complex a = { 3, 4 }, b, *c;
    10
    11      printf("&a = %p t a.real = %d t a.imag = %dn", &a, a.real, a.imag);
    12      printf("&a.real = %p t &a.imag = %p nn", &a.real, &a.imag);
    13
    14      b = a;
    15      a.real = 5;
    16      a.imag = 6;
    17      printf("&b = %p t b.real = %d t b.imag = %dn", &b, b.real, b.imag);
    18      printf("&b.real = %p t &b.imag = %p nn", &b.real, &b.imag);
    19
    20      c = &a;
    21      a.real = 7;
    22      a.imag = 8;
    23      printf("c = %p t c->real = %d t c->imag = %dn", c, c->real, c->imag);
    24  }

#49 enterprise:/data1/student/c9844000% a.out
&a = effff9e4    a.real = 3      a.imag = 4
&a.real = effff9e4       &a.imag = effff9e8 

&b = effff9dc    b.real = 3      b.imag = 4
&b.real = effff9dc       &b.imag = effff9e0 

c = effff9e4     c->real = 7     c->imag = 8


중첩된 struct

struct S {
        struct T { int a, b; } x;
};
struct S a;
a.x.a = 10;
a.x.b = 20;

예제: nestedstruct.c
     1  #include <stdio.h>
     2
     3  main() {
     4      struct  S {
     5          struct  T {
     6              int a;
     7              int b;
     8          } x;
     9          int  y;
    10      };
    11
    12      struct S a = { { 10, 20}, 30 };
    13
    14      printf("a.x.a = %dn", a.x.a);
    15      printf("a.x.b = %dn", a.x.b);
    16      printf("a.y = %dn", a.y);
    17  }

#5 enterprise:/data1/student/c9844000% a.out
a.x.a = 10
a.x.b = 20
a.y = 30


struct의 각 컴포넌트의 포인터
struct vector3 {
        int x;
        int y;
        int z;
} s;
int  *p, *q, *r;
....
p = &s.x;
q = &s.y;
r = &s.z;

구조체와 함수
예제: passing_struct.c
     1  #include <stdio.h>
     2
     3  struct da {
     4      int x,y,z;
     5  };
     6
     7  int total ( struct da tot ) {
     8      return ( tot.x + tot.y + tot.z );
     9  }
    10
    11  main() {
    12      struct da val = { 10, 30, 50 };
    13      int sum = 0;
    14      sum = total ( val );
    15      printf("Sum = %dn",sum);
    16  }

#62 enterprise:/data1/student/c9844000% a.out
Sum = 90

예제: passing_pointer.c
     1  #include <stdio.h>
     2
     3  struct da {
     4      int x, y, z;
     5  };
     6
     7  int total ( struct da *tot) {
     8      return ( tot->x + tot->y + tot->z );
     9  }
    10
    11  void main(void) {
    12      struct da val = { 10, 30, 50 };
    13      int sum = 0;
    14      sum = total (&val);
    15      printf("Sum = %dn",sum);
    16  }

#65 enterprise:/data1/student/c9844000% a.out
Sum = 90


구조체 크기
예제: struct_size1.c
     1  #include <stdio.h>
     2
     3  main() {
     4      struct  S {
     5          char  c1;
     6          char  c2;
     7      };
     8
     9      struct S a;
    10
    11      printf("sizeof(S) = %dn", sizeof(a));
    12  }
#89 enterprise:/data1/student/c9844000% a.out
sizeof(S) = 2

예제: struct_size2.c
     1  #include <stdio.h>
     2
     3  main() {
     4      struct  S {
     5          char  c1;
     6          char  c2;
     7          int   a;
     8      };
     9
    10      struct S a;
    11
    12      printf("sizeof(S) = %dn", sizeof(a));
    13      printf("&a.c1 = %p n", &a.c1);
    14      printf("&a.c2 = %p n", &a.c2);
    15      printf("&a.a = %p n", &a.a);
    16  }
#95 enterprise:/data1/student/c9844000% a.out
sizeof(S) = 8
&a.c1 = effff9e4 
&a.c2 = effff9e5 
&a.a = effff9e8 


예제: struct_size.c
     1  #include <stdio.h>
     2
     3  main() {
     4      struct  S {
     5          char  c1;
     6          char  c2;
     7          int   value[5];
     8      };
     9
    10      struct S a;
    11
    12      printf("sizeof(S) = %dn", sizeof(a));
    13  }

#71 enterprise:/data1/student/c9844000% a.out
sizeof(S) = 24


student.c
     1  #include <stdio.h>
     2
     3  struct student {
     4      char name[20];
     5      int  age;
     6      int  year;
     7      struct student * next;
     8  };
     9
    10  main() {
    11      struct student a, *p, *i;
    12
    13      strcpy(a.name, "Hong Gil Dong");
    14      a.age = 22;
    15      a.year = 1;
    16      a.next = NULL;
    17
    18      p = (struct student *) malloc(sizeof(struct student));
    19      strcpy(p->name, "Lee Soong Sil");
    20      p->age = 22;
    21      p->year = 1;
    22      p->next = NULL;
    23
    24      a.next = p;
    25      i = &a;
    26
    27      while(i != NULL) {
    28          printf("i->name :%sn", i->name);
    29          printf("i->age :%dn", i->age);
    30          printf("i->year :%dn", i->year);
    31          i = i->next;
    32          printf("n");
    33      }
    34  }

#33 enterprise:/data1/student/c9844000% a.out
i->name :Hong Gil Dong
i->age :22
i->year :1

i->name :Lee Soong Sil
i->age :22
i->year :1


예제: dynamic_student.c
     1  #include <stdio.h>
     2
     3  struct student {
     4      char name[50];
     5      int  age;
     6      int  year;
     7      struct student * next;
     8  };
     9
    10  main() {
    11      struct student *p, *head, *temp;
    12      char name[50], end;
    13      int  age, year;
    14
    15      head = p = temp = NULL;
    16      while(1) {
    17          printf("put name:");
    18          gets(name);
    19          printf("put age:");
    20          scanf("%d", &age);
    21          printf("put year:");
    22          scanf("%d", &year);
    23          temp = (struct student *) malloc(sizeof(struct student));
    24          if(head == NULL) {
    25              head = temp;
    26              p = temp;
    27          } else {
    28              p->next = temp;
    29          }
    30          strcpy(temp->name, name);
    31          temp->age = age;
    32          temp->year = year;
    33          temp->next = NULL;
    34
    35          getchar();
    36          printf("Do you want more data ? (Y/N):");
    37          end = getchar();
    38
    39          if(end == 'N' || end == 'n')
    40              break;
    41      }
    42
    43      temp = head;
    44      printf("nn=====================================n");
    45      while(temp) {
    46          printf("temp->name :%sn", temp->name);
    47          printf("temp->age :%dn", temp->age);
    48          printf("temp->year :%dn", temp->year);
    49          temp = temp->next;
    50          printf("n");
    51      }
    52  }

#165 enterprise:/data1/student/c9844000% a.out
put name:Son Oh Gong
put age:22
put year:1
Do you want more data ? (Y/N):
put name:Sa Oh Jung
put age:21
put year:1
Do you want more data ? (Y/N):n


=====================================
temp->name :Son Oh Gong
temp->age :22
temp->year :1

temp->name :Sa Oh Jung
temp->age :21
temp->year :1


공용체(UNION)

union  name {
        type  name;
        type  name;
};

     1  #include <stdio.h>
     2  #define AGE  1
     3  #define YEAR 2
     4
     5  union Information {
     6      int  age;
     7      int  year;
     8  };
     9
    10  struct  student {
    11      char name[20];
    12      int infortype;
    13      union Information value;
    14      struct student * next;
    15  };
    16
    17  main() {
    18      struct student lee, *p, *i;
    19
    20      lee.infortype = AGE;
    21      strcpy(lee.name, "Lee Soong Sil");
    22      lee.value.age = 22;
    23      lee.next = NULL;
    24
    25      p = (struct student *)malloc(sizeof(struct student));
    26      strcpy(p->name, "Hong Gil Dong");
    27      p->infortype = AGE;
    28      p->value.age = 22;
    29      p->next = NULL;
    30      lee.next = p;
    31      i = p;
    32
    33      p = (struct student *)malloc(sizeof(struct student));
    34      p->infortype = YEAR;
    35      strcpy(p->name, "Sa Oh Jung");
    36      p->value.year = 1;
    37      p->next = NULL;
    38      i->next = p;
    39
    40      i = &lee;
    41      while(i) {
    42          printf("i->name : %sn", i->name);
    43          if(i->infortype == AGE)
    44              printf("i->value(age) : %dn", i->value.age);
    45          else if(i->infortype == YEAR)
    46              printf("i->value(year) : %dn", i->value.year);
    47          else
    48              printf("Invalid data typen");
    49
    50          printf("n");
    51          i = i->next;
    52      }
    53  }

#53 enterprise:/data1/student/c9844000% a.out
i->name : Lee Soong Sil
i->value(age) : 22

i->name : Hong Gil Dong
i->value(age) : 22

i->name : Sa Oh Jung
i->value(year) : 1


?

List of Articles
번호 분류 제목 글쓴이 날짜 조회 수
841 Develop '2014 모바일 개발 트렌드' 발표자료입니다. file hooni 2014.10.02 1137
840 Develop Aspect Oriented Programming in Objective-C hooni 2015.05.18 948
839 Develop DDay Memo 1.9.4 소스코드 secret hooni 2015.10.03 0
838 Develop GCM 사용하기 2 (단말에 GCM 구현하기) file hooni 2013.07.06 23411
837 Develop GCM 사용하기 3 (JSP로 GCM 푸시 서버 만들기) 4 file hooni 2013.07.06 25425
836 Develop git 브런치 배우기 (링크) hooni 2013.07.09 20701
835 Develop GPL, AGPL, MPL,.. 한눈에 보는 오픈소스SW 라이선스 file hooni 2014.10.14 1265
834 Develop How to Test SMTP AUTH using Telnet hooni 2018.04.05 1589
833 Develop JSON, BSON 변환 file hooni 2013.04.23 11873
832 Develop Laravel 5 Failed opening required bootstrap/../vendor/autoload.php hooni 2018.01.24 1834
831 Develop Mac OS 에 Jenkins 설치하기 (Homebrew) 2 file hooni 2017.03.15 8395
830 Develop macOS에 node, npm 설치하기 (homebrew) file hooni 2021.11.06 1459
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 71 Next
/ 71