C++ Algorithm & Study/C++ & Algorithm Strategies

[C++] 3 - 기초 문법 공부 일지(Pointer)

GameChoi 2022. 11. 29. 23:06
  • Pointer
    • 포인터 - 주소 값
    • 주소 값을 따라가면 원하는 값을 찾을 수 있음
int main()
{

	int hp = 100;

	int* ptrHp = &hp;
	cout << ptrHp << endl; // 원하는 값의 주소 값
	cout << *ptrHp << endl; // 100

	int** pptrHp = &ptrHp;

	cout << pptrHp << endl; // 원하는 값의 주소 값
	cout << *pptrHp << endl; // ptrHp의 주소 값
	cout << **pptrHp << endl; // 100
 }
  • Reference
    • 복사 전달 방식
    • 주소 전달 방식
    • 참조 전달 방식
struct StatInfo
{
	int hp;
	int damage;
}; // pch.h

void StatInfoByCopy(StatInfo player)
{
	cout << player.hp << ", " << player.damage << endl;
}

void StatInfoByPointer(StatInfo* player)
{
	if (player == nullptr) return; // 값이 있는 지 확인 - 주소를 보고 쓰레기 값이 있을 수 도있음.

	cout << (*player).hp << ", " << (*player).damage << endl; // pointer 활용
	cout << player->hp << ", " << player->damage << endl; // -> 활용
}

void StatInfoByReference(const StatInfo& player)
{
	// const 사용 이유 - 원본 데이터를 사용하지 않는 경우 건드리지 못하게 하기 위함
	cout << player.hp << ", " << player.damage << endl;
}

int main()
{
	StatInfo player{ 100, 20 };
	cout << player.hp << ", " << player.damage << endl;

	StatInfoByCopy(player); // 값을 복사해 전달
	StatInfoByPointer(&player); // 값의 주소 값을 전달
	StatInfoByReference(player); // 값의 원본을 전달
}
  • Array
int main()
{
	const int count = 10;
	int inventory[count];

	for (int i = 0; i < count; i++) // for 사용
		inventory[i] = i;


	int inventoryList = 0;
	for (int& i : inventory) // range-base for 및 참조 사용
	{
		i = inventoryList++;
		cout << inventory[i] << endl;
	}
}