Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 | 31 |
Tags
- const
- Class
- 문자열
- 함수
- 백준
- 배열
- pass by reference
- programming
- 오블완
- 포인터
- Pre-processing
- function
- Python
- raw data
- assignment operator
- OOP
- Deep Learning
- Data Science
- pointer
- vscode
- 파이썬
- 알고리즘
- baekjoon
- C++
- string
- array
- Object Oriented Programming
- predictive analysis
- 티스토리챌린지
- 반복문
Archives
- Today
- Total
Channi Studies
[C++] 데이터의 주소에 접근하는 방법 본문
C++에서는 & 기호를 통해 데이터의 주소에 접근할 수 있습니다.
값은 16진수 숫자로 반환됩니다.
예시를 보여드리겠습니다.
#include <iostream>
using namespace std;
int main() {
int num{10};
cout << "Value of num is: " << num << endl;
cout << "sizeof num is: " << sizeof(num) << endl;
cout << "Address of num is: " << &num << endl;
return 0;
}

비슷한 예시를 포인터에 적용하면 다음과 같습니다.
#include <iostream>
using namespace std;
int main() {
int *p;
cout << "Value of num is: " << p << endl;
cout << "Address of num is: " << &p << endl;
cout << "sizeof num is: " << sizeof(p) << endl;
p = nullptr;
cout << "Value of num is: " << p << endl;
return 0;
}

포인터 p를 선언할 때, 초기화를 하지 않았기 때문에 초기에는 garbage data가 들어있어서
이상한 value가 들어 있었습니다.
이후 p = nullptr; 를 통해서 값을 0으로 변경하였습니다.
중요한 것은 sizeof(pointer) 의 상황입니다.
아시다시피 포인터는 다른 변수 혹은 함수의 위치값을 저장하고 있는 변수입니다.
즉, sizeof(pointer)의 값은 포인터가 가르키는 주소에 있는 변수 타입과는 무관합니다.
다시 말하자면, 각 포인터가 가르키는 값의 타입과 포인터의 용량은 무관합니다.
모든 포인터에게 sizeof 함수를 적용한 값은 전부 동일하게 나타납니다.
#include <iostream>
int main() {
int *p1{nullptr};
double *p2{nullptr};
unsigned long long *p3{nullptr};
vector<string> *p4{nullptr};
string *p5{nullptr};
cout << "\nsizeof p1 is: " << sizeof p1 << endl;
cout << "sizeof p2 is: " << sizeof p2 << endl;
cout << "sizeof p3 is: " << sizeof p3 << endl;
cout << "sizeof p4 is: " << sizeof p4 << endl;
cout << "sizeof p5 is: " << sizeof p5 << endl;
return 0;
}

하지만 우리는 포인터를 선언할 때 타입도 선언했습니다.
그렇기 때문에 int 타입 포인터에 double 타입 값에 대한 주소를 저장할 수 없습니다.
포인터는 선언된 타입과 다른 타입의 값에 대한 주소를 저장할 수 없습니다.
#include <iostream>
int main() {
int score{10};
double high_temp{100.7};
int *score_ptr{nullptr};
score_ptr = &score;
cout << "Value of score is: " << score << endl;
cout << "Address of score is: " << &score << endl;
cout << "Value of score_ptr is: " << score_ptr << endl;
// score_ptr = &high_temp; // Compiler error
cout << endl;
return 0;
}

'C++ > 포인터 (Pointers)' 카테고리의 다른 글
| [C++] 배열과 포인터의 관계 (Relationship Between Arrays and Pointers) (1) | 2023.12.19 |
|---|---|
| [C++] 동적 메모리 할당 (Dynamic Memory Allocation) (1) | 2023.12.19 |
| [C++] 역참조 (Dereferencing a Pointer) (0) | 2023.12.19 |
| [C++] 포인터의 선언 (Declaring Pointers) (0) | 2023.12.19 |
| [C++] 포인터(Pointer)란? (0) | 2023.12.19 |