열렬히.뛰기

구조체

Language > 프로그래밍 언어 > C > 구조체

구조체

자료형의 구분

  • 기본자료형 : int, char, double, void 등등
  • 파생자료형 : 배열, 포인터, 구조체, 공용체

배열 = 같은 종류의 데이터를 하나로 묶는다.

구조체 = 다른 종류의 데이터를 하나로 묶는다.

구조체 사용하기

c
#include <stdio.h>
#include <stdlib.h>

// 먼저 구조체 선언을 한다.
struct student { // 구조체 태그
        int number;    // 구조체 멤버
        char name[10]; // 구조체 멤버
        double grade;  // 구조체 멤버
};

int main() {
        struct student s; // 구조체 변수를 생성한다.

        s.number = 20190001; // 구조체를 참조한다.
        strcpy(s.name, "홍길동");
        s.grade = 4.3;

        printf("학번 : %d\n", s.number);
        printf("이름 : %s\n", s.name);
        printf("성적 : %d\n", s.grade);

}

구조체의 활용

구조체 안의 구조체를 만들어보자.

c
#include <stdio.h>

struct point {
        int x;
        int y;
};

struct rect {
        struct point p1;
        struct point p2;
};

int main() {
        struct rect r;
        int w, h, area, peri;

        printf("좌표1 입력 : ");
        scanf("%d %d", &r.p1.x, &r.p1.y);

        printf("좌표2 입력 : ");
        scanf("%d %d", &r.p2.x, &r.p2.y);

        w = r.p2.y - r.p1.x;
        h = r.p2.y - r.p1.x;
				
        printf("면적 : %d / 둘레 : %d", w*h, 2*(w+h));

}

구조체 역시 연산이 가능하다.

c
struct point { 
				int x;
				int y;
}

struct point p1 = {10, 20};
struct point p2 = {30, 40};
p2 = p1;
p2.x = p1.x;

단, 구조체 변수와 구조체 변수 자체를 비교하는 것은 불가능.

c
/* 문법 오류
if (p1 == p2) {
				printf("");
}*/

if (p1.x == p2.x) {
				printf("");
}

구조체를 배열화하는 것 역시 가능하다.

c
struct student {
			int number;
			char name[20];
			double grade;
}

struct student list[100];

list[2].number = 24;
strcpy(list[2].name, "홍길동"); // 문자열은 항상 strcpy()를 이용, 대입.
list[2].grade = 4.3;


// 구조체 배열의 초기화
struct student list[3] = {
			{1, "Park", 23},
			{2, "Kim", 25}
};

구조체와 포인터

구조체에서 포인터가 사용되는 경우는 다음 2가지이다.

  1. 구조체를 가리키는 포인터
  2. 포인터를 포함하는 구조체
c

p = &s;
(*p).number = 12; // 접근방식 1
p -> number = 12; // 접근방식 2


// 포인터를 포함하는 구조체
struct x {
				int number;
				char name[20];
				struct student *dob
}

int main() {
				// 구조체를 가리키는 포인터
				struct student s = { 24, "kim", 4.3 };
				struct student *p;

				s.dob = &d;
				s.dob -> age;
}

구조체 안에 문자열을 저장하는 두가지 방법이 있다.

c
struct A {
				int number;
				char name[10];
				double grade;
};

struct B {
				int number;
				char p*;
				double grade;
};

int main() {
				struct A s1 = { 20180001, "홍길동", 4.3 };
				struct B s2 = { 20192313, "김유신", 4.2 };
}

s1 → 구조체 내부의 배열에 저장.

s2 → 구조체에는 포인터만 저장. 포인터 p가 문자열을 가르켜야 함.

구조체와 함수

c
// 구조체를 인수로 쓰기
int equal(struct student s1, struct student s2) {...}
int main() {
		struct student a = {...}
		struct student a = {...}
		if equal(a, b) == 1 {...}
}
c
// 구조체의 포인터를 인수로 쓰기
int equal(struct student *p1, struct student *p2) {...}
int main() {
		struct student a = {...}
		struct student a = {...}
		if equal(&a, &b) == 1 {...}
}
c
// 구조체를 함수의 반환 값으로 넘기기
struct student create() {
		struct student s;
		s.number = 3;
		strcpy(s.name, "park");
		s.grade = 3;
		return s;
}
int main() {
		struct student a;
		a = create();
}

공용체

같은 메모리 영역을 여러 개의 변수들이 공유하는 기능. 메모리를 절약하는데 사용

단 동시에 모든 멤버 변수들의 값을 저장할 수 없으면 하나의 멤버만 저장.

c
union example {
		char c;
		int i;
		// 어떤 순간에는 둘 중 하나만 존재한다.
};

int main() {
		union example v = {"asdf"};
}

열거형

변수가 가질 수 있는 값들을 나열해 놓은 자료.

프로그램의 이해도를 높이고, 오류를 줄여준다.

c
enum days { SUN, MON, TUE, WED, THU, FRI, SAT}

typedef

새로운 자료형을 정의하는 것.

c
typedef unsigned char BYTE;

구조체로도 새 자료형을 만들 수 있다.

c
typedef struct complex {
			double real;
			double imagine;
} COMPLEX;

COMPLEX x, y;