C&&C++/C,C++ learning
[C++] 구조체
rudgh99_algo
2024. 8. 30. 19:42
1. 사용법
#include <bits/stdc++.h>
using namespace std;
int main(void) {
ios::sync_with_stdio(0);
cin.tie(0);
struct position {
int xpos;
int ypos;
};
struct position pos;
pos.xpos = 1;
pos.ypos = 2;
cout << pos.xpos << ' ';
}
정확하지는 않지만, 비유를 해보면 , position이라는 클래스의 이름에 객체를 생성한다. 이때 객체의 이름은 pos다. 각각의 메서드에 접근하기 위해서는. 을 이용해 멤버변수에 접근한다. (그냥 내가 이해하기 쉽도록 작성)
구조체를 정의 후 선언하는 방법;
#include <bits/stdc++.h>
using namespace std;
int main(void) {
ios::sync_with_stdio(0);
cin.tie(0);
struct position {
int xpos;
int ypos;
} pos1, pos2;
}
2. 구조체 값을 초기화하는 방법
#include <bits/stdc++.h>
using namespace std;
int main(void) {
ios::sync_with_stdio(0);
cin.tie(0);
struct position {
int xpos;
int ypos;
} pos1, pos2;
pos1 = { 10,20 };
cout << pos1.xpos << ' ';
}
3. 구조체 배열
#include <bits/stdc++.h>
using namespace std;
int main(void) {
ios::sync_with_stdio(0);
cin.tie(0);
struct position {
int xpos;
int ypos;
};
struct position posarr[3];
for (int i = 0; i < sizeof(posarr)/sizeof(position); i++) {
int x, y;
cin >> x >> y;
posarr[i] = { x,y };
}
for (int i = 0; i < sizeof(posarr) / sizeof(position); i++) {
cout << posarr[i].xpos << ' ' << posarr[i].ypos << '\n';
}
}
sizeof(position) = sizeof(int) + sizeof(int) = 4 + 4 = 8 bytes
sizeof(posarr) = sizeof(position) * 3 = 24 bytes
구조체 배열의 값을 초기화하는 방법
#include <bits/stdc++.h>
using namespace std;
int main(void) {
ios::sync_with_stdio(0);
cin.tie(0);
struct position {
int xpos;
int ypos;
};
struct position posarr[3] = { {1,2},{3,4},{5,6} };
}
4. 구조체 포인터
#include <bits/stdc++.h>
using namespace std;
int main(void) {
ios::sync_with_stdio(0);
cin.tie(0);
struct position {
int xpos;
int ypos;
};
struct position pos;
struct position* ptr;
ptr = &pos;
(*ptr) = { 1,2 };
cout << (*ptr).ypos << ' ';
}
포인터로 구조체를 가리킬 때 , 실제 자주 사용되는 표현
#include <bits/stdc++.h>
using namespace std;
int main(void) {
ios::sync_with_stdio(0);
cin.tie(0);
struct position {
int xpos;
int ypos;
};
struct position pos;
struct position* ptr;
ptr = &pos;
ptr->xpos = 3;
ptr->ypos = 2;
cout << ptr->ypos << ' ';
}
자료 출처 : https://cafe.naver.com/cstudyjava
윤성우의 프로그래밍 스터디그룹 [C/... : 네이버 카페
윤성우의 스터디 공간입니다. C와 JAVA를 공부하시는 분들은 모두 들어오세요. ^^
cafe.naver.com