본문 바로가기
언어 공부/C++

구조체(struct)

by 세희홍 2022. 6. 29.

구조체

공통된 부분들을 하나의 그룹으로 묶어서 자료를 관리하기 위해 사용한다. 배열과 달리 타입이 달라도 된다. 

#include  <iostream>
using namespace std;
struct Student {
	int id;
	char name[20];
	float grade[2];
};
int main() {
	// 구조체 배열
	Student sInfos[4] = {
		{202001, "Lee", {4.3f, 4.1f}},
		{202020, "Choi", {3.3f, 4.0f}},
		{202041, "Park", {3.5f, 3.1f}},
		{202023, "Kin", {3.3f, 4.1f}}
	};
	for (auto i = 0; i < 4; i++) {
		cout << sInfos[i].id << endl; // 202001
		cout << sInfos[i].name << endl; // Lee
		cout << sInfos[i].grade[0] << endl; // 4.3
		cout << sInfos[i].grade[1] << endl; // 4.1
	}

	return 0;
}

 

구조체 포인터

#include  <iostream>
using namespace std;
struct Rectangle {
	int x, y;
	int w, h;
};
int main() {
	Rectangle r = { 15, 10, 50, 70 };
	Rectangle* pr = &r; // 구조체 포인터

	cout << r.x << " " << (*pr).x << endl; // 15 15
	cout << (*pr).y << " " << pr->y << endl; // 10 10
	cout << (*pr).h << " " << pr->h << endl; // 70 70
	pr->h = 40;
	(*pr).w = 100;
	cout << (*pr).h << " " << pr->h << endl; // 40 40
	cout << r.w << " " << pr->w << endl; // 100 100


	return 0;
}

 

Linked List 구현

#include  <iostream>
using namespace std;
struct LinkedList {
	int data;
	LinkedList* p;//구조체 포인터. 구조체의 주소 담는다.
};
int main() {
	LinkedList a, b, c;
	a.data = 99;
	a.p = &b;
	b.data = 93;
	b.p = &c;
	c.data = 94;
	c.p = &a;

	cout << c.data << endl; // 94
	cout << b.p->data << endl; // 94
	cout << (*b.p).data << endl; // 94
	cout << a.p->p->data << endl; // 94
	cout << c.p->p->p->data << endl; // 94

	return 0; 
}

 

 

 

 

 

'언어 공부 > C++' 카테고리의 다른 글

열거체(enumeration)  (0) 2022.06.29
공용체(Union)  (0) 2022.06.29
다형성(Polymorphism)  (0) 2022.06.27
클래스 간의 관계: 의존  (0) 2022.06.26
클래스 간의 관계: 연관  (0) 2022.06.26

댓글