[C++] Pointer & Reference

JAsmine_log·2024년 5월 19일

C++

Pointers

*는 메모리 주소(memory address)를 저장하는 변수이다.
포인터 변수는 데이터 타입(int 또는 string)을 지정하여 생성하고, 변수의 주소는 포인터로 할당한다.

#include <iostream>
using namespace std;

int main(){
    
    string colors = "red"; // A colors variable of type string
    string* ptr = &colors; 

    // Output the value of colors (red)
    cout << colors << endl;
    
    // Output the memory address of colors (0x7ffda7e33180)
    cout << &colors << endl;
    
    // Output the memory address of colors with the pointer (0x7ffda7e33180)
    cout << ptr << endl;
    
    return 0;
}

>> 
red
0x7ffda7e33180
0x7ffda7e33180

Refrences

&는 변수의 메모리 주소에 접근할 수 있게 한다.
참조 변수는 존재하는 변수(value)를 참조한다. 이를 통해서, colors 변수나 rgb 변수에 이름으로 접근하여 값을 확인할 수 있다.

#include <iostream>
using namespace std;

int main(){
    
    string colors = "red";  // colors variable
    string &rgb = colors;    // reference to colors

    cout << colors << endl;  // Outputs colors
    cout << rgb << endl;  // Outputs colors
    
    return 0;
}

>> 
red
red

Refrence

[1] https://www.w3schools.com/cpp/cpp_pointers.asp
[2] https://www.w3schools.com/cpp/cpp_references.asp

profile
Everyday Research & Development

0개의 댓글