Nathan
Nathan

Reputation: 78439

Variable references

I'm learning about references and pointers, and something in the tutorial isn't compiling for me (I'm using GCC).

Okay, here is the code:

#include <iostream>

using namespace std;

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

ted = &andy;

cout << "ted: " << ted << endl;
cout << "andy: " << andy << endl;
}

The compiler output says "error: invalid conversion from 'int*' to 'int'" I also tried a string = v; v = &andy; but that didn't work either.

How can I assign the memory address to a variable?

Upvotes: 1

Views: 64

Answers (2)

Pubby
Pubby

Reputation: 53047

An int pointer is a different type than an int. You can't assign pointers to integers without some nasty tricks. I'll give you some examples of what you likely want to do.

Example of a pointer:

#include <iostream>

using namespace std;

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

int * ptr = &andy;

cout << "ted: " << ted << endl;
cout << "andy: " << andy << endl;
cout << "ptr: " << *ptr << endl;
}

Example of a reference:

#include <iostream>

using namespace std;

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

int & ref = andy;

cout << "ted: " << ted << endl;
cout << "andy: " << andy << endl;
cout << "ref: " << ref << endl;
}

Upvotes: 0

hmjd
hmjd

Reputation: 121971

A pointer holds a memory address. In this case, you need to use a pointer to an int: int*.

For example:

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'

Upvotes: 5

Related Questions