3. 포인터
1. 포인터
#include <iostream>
using namespace std;
int main() {
int number1 = 10;
int *pointer1 = &number1;
double number2 = 23.4;
double *pointer2 = &number2;
cout << "number1: " << number1
<< " (size: " << sizeof(number1) << ")" << endl;
cout << "pointer1: " << pointer1
<< " (size: " << sizeof(pointer1) << ")" << endl;
cout << "number2: " << number2
<< " (size: " << sizeof(number2) << ")" << endl;
cout << "pointer2: " << pointer2
<< " (size: " << sizeof(pointer2) << ")" << endl;
return 0;
}
2. 포인터 변수
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int PointerFunc(vector<string> *);
int main() {
vector<string> message;
message.push_back("고려 장군");
message.push_back("척준경!");
message.push_back("절친 이름은");
message.push_back("... 무엇일까");
cout << "포인터 인자 크기: " << PointerFunc(&message) << endl;
cout << "원래 변수 크기: " << sizeof(message) << endl;
return 0;
}
int PointerFunc(vector<string> *info) {
if (info->empty() == true)
return 0;
else
return sizeof(info);
}
3. 포인터 배열
#include <iostream>
using namespace std;
int main() {
const int SIZE = 3;
int numbers[SIZE] = {10, 20, 30};
int *pointer1 = numbers;
int no1 = 1;
int no2 = 2;
int no3 = 3;
int *pointer2[SIZE] = {&no1, &no2, &no3};
for (int i = 0; i < SIZE; i++)
cout << "Pointer1[" << i << "] = " << *(pointer1 + i) << endl;
for (int i = 0; i < SIZE; i++)
cout << "Pointer2[" << i << "] = " << *pointer2[i] << endl;
return 0;
}
4. Call by Value
5. Call by Reference
#include <iostream>
#include <string>
using namespace std;
void Func1(int &);
void Func2(string &);
int main() {
int year = 10;
Func1(year);
cout << "Func1 함수 종료 후: " << year << endl;
string king_info = "고려 성종 즉위년: ";
Func2(king_info);
cout << king_info << endl;
return 0;
}
void Func1(int &arg) {
cout << "변경 전: " << arg << endl;
arg += 10;
cout << "변경 후: " << arg << endl;
}
void Func2(string &info) {
info += "981년";
}
6. Call by Address
#include <iostream>
using namespace std;
void Func1(bool *);
void Func2(bool &is_on);
int main() {
bool is_tmp = true;
Func1(&is_tmp);
Func2(is_tmp);
return 0;
}
void Func1(bool *is_on) {
cout << "Call by Address: " << sizeof(is_on) << endl;
}
void Func2(bool &is_on) {
cout << "Call by Reference: " << sizeof(is_on) << endl;
}
7. const
변수
8. const
포인터
#include <iostream>
using namespace std;
int main() {
int number1 = 10;
int number2 = 20;
const int number3 = 30;
const int number4 = 40;
int *ptr1 = &number1;
*ptr1 = 100;
ptr1 = &number2;
cout << "int *ptr1은 "
<< "가리키는 주소와 해당 주소의 값을 "
<< "모두 변경할 수 있습니다."
<< endl;
int *const ptr2 = &number1;
*ptr2 = 10;
// ptr2 = &number2;
cout << "int *const ptr2는 "
<< "해당 주소의 값은 변경할 수 있지만, "
<< "가리키는 주소는 변경할 수 없습니다." << endl;
const int *ptr3 = &number3;
// *ptr3 = 100;
ptr3 = &number4;
cout << "const int *ptr3은 "
<< "가리키는 주소는 변경할 수 있지만, "
<< "해당 주소의 값은 변경할 수 없습니다." << endl;
int const *ptr4 = &number3;
// *ptr4 = 100;
ptr4 = &number4;
cout << "int const *ptr4는 "
<< "const int *ptr3과 같습니다." << endl;
return 0;
}