变量引用

Nat*_*han 1 c++ pointers

我正在学习引用和指针,本教程中的内容并没有为我编译(我正在使用GCC).

好的,这是代码:

#include <iostream>

using namespace std;

int main()
{
int ted = 5;
int andy = 6;

ted = &andy;

cout << "ted: " << ted << endl;
cout << "andy: " << andy << endl;
}
Run Code Online (Sandbox Code Playgroud)

编译器输出显示"错误:从'int*'到'int'的无效转换"我也尝试了一个string = v; v =&andy; 但那也不起作用.

如何将内存地址分配给变量?

hmj*_*mjd 5

指针保存内存地址.在这种情况下,您需要使用指向int的指针:int*.

例如:

int* ptr_to_int;

ptr_to_int = &andy;

std::cout << ptr_to_int  << "\n"; // Prints the address of 'andy'
std::cout << *ptr_to_int << "\n"; // Prints the value of 'andy'
Run Code Online (Sandbox Code Playgroud)