반응형
▶ 이전강의
- 바로가기
[C++] 8. 배열과 포인트 연산
▶ 이전강의- 바로가기 [C++] 7. 포인터▶ 이전강의- 바로가기 [C++] 6. TextRPG 레벨업 시스템 - 완성▶ 이전 학습- 바로가기 [C++] 5. TextRPG 아이템 능력치 적용▶ 이전 학습- 바로가기 [C++] 4. TextRPG 아
lhy-info.tistory.com
▶ Char 포인터
const char* pText = "text";
cout << "pText 주소 : " << (int*)pText << endl; //pText의 주소
pText = "texts";
cout << "pText 주소 : " << (int*)pText << endl; //pText의 주소
pText = "texts";
cout << "pText 주소 : " << (int*)pText << endl; //pText의 주소
pText = "textsss";
cout << "pText 주소 : " << (int*)pText << endl; //pText의 주소
- const를 바꾸면 문자열로 저장할 수 있음
- 값을 바꾸면 메모리 주소가 바뀜
▶ 구조체 포인터
cout << "ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ구조체 포인터: " << endl;
_tagStudent student = {};
student.iKor = 100;
cout << "student.iKor : " << student.iKor << endl; //100
_tagStudent* pStudent = &student;
(*pStudent).iKor = 50;
cout << "student.iKor : " << student.iKor << endl; //50
// ->을 이용해 가르키는 대상의 맴버에 접근 가능
pStudent->iKor = 80;
cout << "student.iKor : " << student.iKor << endl; //80
- 연산자 우선순위 때문에 .을 먼저 인식함
- 메모리 주소 .은 잘못된 문법이며 *pStudent를 괄호로 감싸잔 후
- .을 이용해 가리크는 대상의 맴버변술에 접근해야함
▶ void 포인터
- void란? 타입이 없다.
- void* 변수를 선언하면 모든 타입이든 메모리주소든 가르킬 수 있다.
cout << "ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡvoid 포인터: " << endl;
void* pvoid = &iInt;
cout << "iInt 주소 : " << &iInt << endl; //iInt의 주소
cout << "pvoid 주소 : " << pvoid << endl; //pvoid의 주소
cout << endl;
cout << "역참조 전 iInt 값 : " << iInt << endl; //iInt의 주소
// 단, 역참조가 불가능하고 메모리 주소만 저장 가능
//*pvoid = 10; //역참조 불가능
int* pConvefrt = (int*)pvoid; //형변환을 해줘야 역참조 가능
*pConvefrt = 10; //역참조 가능
cout << "역참조 후 iInt 값 : " << iInt << endl; //iInt의 주소
*((int*)pvoid) = 20; //역참조 가능
cout << "역참조 후 iInt 값 : " << iInt << endl; //iInt의 주소
cout << endl;
pvoid = &pStudent;
cout << "pStudent 주소 : " << &pStudent << endl; //pStudent의 주소
cout << "pvoid 주소 : " << pvoid << endl; //pvoid의 주소
- void는 모든 주소와 타입을 담을 수 있지만 역참조가 불가능하고 메모리 주소만 저장 가능
- 역참조를 위해선 형변환을 해줘야함
반응형
'C++ > C++입문' 카테고리의 다른 글
[C++] 11. 함수와 변수 (0) | 2025.04.10 |
---|---|
[C++] 10. 이중포인터 (0) | 2025.04.09 |
[C++] 8. 배열과 포인트 연산 (0) | 2025.04.08 |
[C++] 7. 포인터 (0) | 2025.04.08 |
[C++] 6. TextRPG 레벨업 시스템 - 완성 (0) | 2025.04.04 |