c++ - 变量引用

标签 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;
}

编译器输出显示“错误:从‘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/

相关文章:

c++ - 如何测量队列中每秒弹出/推送的速率?

c++ - 在 C++ 中使用 gnuplot-iostream.h

c++ - 值(value)观出现偏差?

c++ - C++中的指针结构和动态内存分配

c - 如何在函数内初始化 Struct 指针数组?

带有 QList 的 C++ 多客户端 TCP 服务器

c++ - 强制局部变量默认初始化

c++ - C 预处理器作为语言创建工具的长度/限制是什么?我在哪里可以了解更多关于这些的信息?

C 指针指向错误的对象

c++ - 对于 vector ,为什么更喜欢迭代器而不是指针?