2012-03-25 50 views
1

我正在學習引用和指針,並且本教程中的某些內容沒有爲我編譯(我正在使用GCC)。變量引用

好,這裏是代碼:

#include <iostream> 

using namespace std; 

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

ted = &andy; 

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

編譯器輸出的說「錯誤:從‘詮釋*’到‘廉政’無效轉換」 我也嘗試了串= V; v = &andy;但這也沒有效果。

如何將內存地址分配給變量?

+0

要非常小心談論引用,當你的意思是指針。 – Matt 2012-03-25 20:50:38

+0

當你指的是指針時,在談論內存地址時也要非常小心。 – Pubby 2012-03-25 20:53:32

回答

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' 
0

一種int指針是不同類型比int。沒有一些討厭的技巧你不能把指針指向整數。我會給你一些你可能想要做的例子。指針的

例如:參考的

#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; 
} 

例子:

#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; 
}