C

구조체

NYoun 2020. 12. 30. 01:35

구조체

  구조체란 여러개의 변수를 묶어 하나의 객체를 표현하고자 할때 사용한다.

 

정의와 선언

struct 구조체명 {
  자료형1 변수명1;
  자료형2 변수명2;
  ...
}

  기본적으로 구조체의 변수에 접근할때는 '.'을 사용한다.

#include <stdio.h>

struct Student{
  char studentId[10];
  char name[10];
  int grade;
  char major[10];
};

int main(void){
  struct Student s;
  strcpy(s.studentId, "20201230");
  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;
}

  위 예제처럼 사용한다.

  s.000은 s로 정의한 Student라는 구조체를 사용하는 것이고 그 안에 studentId, name, grade, major 를 사용할 수 있게

  struct로 정의한다.

  학번 : 20201230

  이름 : 홍길동

  학년 : 4

  학과 : 컴퓨터공학

  이 형태로 출력된다.

 

  하나의 구조체 변수만 사용하는 경우 정의와 동시에 선언을 할 수도 있다.

  이 경우 변수는 전역변수로 사용된다.

struct Student{
  char studentId[10];
  char name[10];
  int grade;
  char major[100];
} s;

  이런 형태로 중괄호가 끝난 뒤에 변수명을 적어주면 된다.

  그럼 위의 예제에서처럼 main 함수내에서 굳이 struct Student s; 의 형태로 정의할 필요가 없어지는 것이다.

 

  그리고 구조체의 변수를 한번에 초기화 할 수도 있다.

struct Student s = { "20201230", "홍길동", 4, "컴퓨터공학" };

  이런 형태로 사용이 가능하고 구조체의 정의와 선언을 동시에 하면서도 값을 바로 넣어줄 수 있다.

  하지만 거의 사용하지 않는 방식이라고 한다.

 

  typedef 키워드를 이용하면 임의의 자료형을 만들 수 있기 때문에 선언이 더 짧아진다.

#include <stdio.h>

typedef struct Student{
  char studentId[10];
  char name[10];
} stu;

int main(void){
  stu s;
  strcpy(s.studentId, "20201230");
  strcpy(s.name, "홍길동");
  printf("학번 : %s\n", s.studentId);
  printf("이름 : %s\n", s.name);
  system("pause");
  return 0;
}

  위 예제처럼 사용한다. 구조체 구문 제일 앞에 typedef를 적어주고 중괄호 바깥에 사용할 이름을 적어준다.

  이렇게 사용한다면 main함수에서 struct Student s; 라고 할 필요 없이 stu s; 로 사용해도 된다는 것이다.

 

  구조체가 포인터 변수로 사용되는 경우에는 내부 변수에 접근할 때 화살표(->)를 사용한다.

#include <stdio.h>

typedef struct Student {
  char studentId[10];
  char name[10];
  int grade;
} stu;

int main(void) {
  stu* s = malloc(sizeof(stu));
  strcpy(s->studentId, "20201230");
  strcpy(s->name, "홍길동");
  s->grade = 4;
  printf("학번 : %s\n", s->studentId);
  printf("이름 : %s\n", s->name);
  printf("학년 : %d\n", s->grade);
  system("pause");
  return 0;
}

  이런 형태로 사용된다. '.'대신 '->'를 사용한다고 생각하면 편하다.

 

 

레퍼런스

패스트캠퍼스 올인원 패키지 - 소프트웨어 베이직