[C++] λ°°μ΄κ³Ό ν¬μΈν°μ κ΄κ³ (Relationship Between Arrays and Pointers)
λ°°μ΄κ³Ό ν¬μΈν°μ κ΄κ³: Relationship Between Arrays and Pointers
λ°°μ΄κ³Ό ν¬μΈν°λ₯Ό λ λ€ μΌμΆ μ΄ν΄νκ² λλ©΄, νκ°μ§ 곡ν΅μ μ μκ² λ©λλ€.
λ°°μ΄μ μ΄λ¦μ΄ μ΄λ€ κ²μ μλ―Ένλμ§ κΈ°μ΅νκ³ κ³μλμ?
λ°λ‘ 'λ°°μ΄μ 첫λ²μ§Έ λ°μ΄ν°μ μ£Όμκ°'μ λνλ λλ€.
κ·Έλ¦¬κ³ , ν¬μΈν° λ³μμ κ°μ μ£Όμκ°μ΄μμ΅λλ€.
μ΄λ κ² λ³΄λ©΄ μ¬μ€μ λ°°μ΄μ μ΄λ¦κ³Ό ν¬μΈν°λ λμΌν κ² κ°μ§ μλμ?
μ€μ λ‘ λ§μ½ ν¬μΈν°κ° λ°°μ΄μ μμμ λμΌν νμ μ κ°μ§κ³ μλ€λ©΄,
ν¬μΈν°μ λ°°μ΄μ μνΈκ΅νμ μΌλ‘, (μ¬μ€μ) λμΌνκ² μ¬μ©ν μ μμ΅λλ€.
κ°λ¨ν μ½λλ‘ μ΄λ₯Ό νμΈν΄ λ³΄κ² μ΅λλ€.
int scores[]{100, 90, 80};
cout << "Print scores: " << scores << endl; // 0x16f11b138 (μ£Όμ)
cout << "Print *scores: " << *scores << endl; // 100
int *score_ptr{scores};
cout << "Print score_ptr: " << score_ptr << endl; // 0x16f11b138 (μ£Όμ)
cout << "Print *score_ptr: " << *score_ptr << endl; // 100
λ°°μ΄μ μ΄λ¦ scoresμ score_ptr ν¬μΈν°κ° λμΌν κΈ°λ₯μ μννκ³ μμμ μ μ μμ΅λλ€.
κ° μμμλ λμΌν λ°©λ²μΌλ‘ μ κ·Όν μ μλμ§ νμΈν΄λ³ΌκΉμ?
int scores[]{100, 90, 80};
int *score_ptr{scores};
cout << score_ptr[0] << endl; // 100
cout << scores[0] << endl; // 100
cout << score_ptr[1] << endl; // 90
cout << scores[1] << endl; // 90
cout << score_ptr[2] << endl; // 80
cout << scores[2] << endl; // 80
μ ννκ² λμΌν λ°©λ²μΌλ‘ ν μ μμμ΅λλ€.
cout << *score_ptr << endl; // 100
cout << *(score_ptr + 1) << endl; // 90
cout << *(score_ptr + 2) << endl; // 80
μ΄λ° κ²λ κ°λ₯ν©λλ€.
μ΄κ² μ΄λ»κ² κ°λ₯νμ§λ μ ν¬μ€νΈ μ€ λ°°μ΄μ κ΄λ ¨λ ν¬μ€νΈμμ λλ΅ μκ°κ° λμ΄μμ΅λλ€.
[C++] λ°°μ΄ (Array)
Modern C++μμλ μ£Όλ‘ λ°°μ΄λ³΄λ€λ 벑ν°λ₯Ό μ¬μ©ν©λλ€. λ°°μ΄μλ μ¬λ¬κ°μ§ νΉμ§μ΄ μ‘΄μ¬ν©λλ€. λνμ μΈ νΉμ§ μ¬λ¬κ°μ§λ₯Ό μκ°ν΄λλ¦¬κ² μ΅λλ€. 1. λ°°μ΄μ λͺ¨λ μμλ€μ κ°μ λ°μ΄ν° νμ μ΄μ¬μΌ
code-studies.tistory.com
미리보기 μ¬μ§μ΄ κ΄λ ¨λ μ€λͺ λΆλΆμ λλ€.
sizeof(int) = 4 μ΄λ―λ‘, μ μ λ°°μ΄μ κ° μμμΈ μ μ νλ λΉ 4μ λ°μ΄νΈλ₯Ό μ°¨μ§ν©λλ€.
μμ μμμμλ κ°μ κ°λ μ΄ μ μ©λμμ΅λλ€.
*score_ptr = score_ptr μ μ£Όμ = scores λ°°μ΄μ 첫λ²μ§Έ κ° (100) μ μ£Όμ μ λλ€.
μ΄λ₯Ό 0x16...10 μ΄λΌκ³ κ°μ νμ λ,
*(score_ptr + 1) = 0x16...10 + 4 = 0x...14
*(score_ptr + 2) = 0x16...10 + 4 + 4 = 0x...18
*(score_ptr + 3) = 0x16...10 + 4 + 4 + 4 = 0x...22
...
μ΄λ° μμΌλ‘ μ§νλ©λλ€.
asteriskλ₯Ό λΌκ³ μ§μ μ μΌλ‘ μ£Όμλ₯Ό νλ² μ½μ΄λ³ΌκΉμ?
int scores[]{100, 90, 80, 70};
int *score_ptr{scores};
cout << score_ptr << endl; // 0x16b00f130
cout << (score_ptr + 1) << endl; // 0x16b00f134
cout << (score_ptr + 2) << endl; // 0x16b00f138
0x16...30, 0x16...34, 0x16...38
λ‘ 4μ© μ¦κ°νλκ² λ³΄μ΄μ€ κ²λλ€.
μ¦, νλμ ννμΌλ‘ μ 리νμλ©΄
array_name λ°°μ΄κ³Ό κ·Έ λ°°μ΄μ κ°λ₯΄ν€λ pointer_name ν¬μΈν°μ λν΄μ,
array_name[index] = *(array_name + index)
pointer_name[index] = *(pointer_name + index)
μ λλ€.