我正在学习引用和指针,教程中的某些内容无法为我编译(我使用的是 GCC)。
好的,这是代码:
#include <iostream>
using namespace std;
int main()
{
int ted = 5;
int andy = 6;
ted = &andy;
cout << "ted: " << ted << endl;
cout << "andy: " << andy << endl;
}
编译器输出显示“错误:从‘int*’到‘int’的无效转换” 我也试过 string = v; v = &andy;但这也没有用。
如何将内存地址分配给变量?
最佳答案
一个指针保存着一个内存地址。在这种情况下,您需要使用指向 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'
关于c++ - 变量引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9863902/