2017-04-08 25 views
1

我見過寫地址的運營商(&)和間接運算符(*)什麼是地址(&)和間接運算符的正確格式

的許多不同的方式如果我不在錯就應該是這樣的:例如,如果你在兩者之間的空間中寫道&var& var

//examples 
int var = 5; 
int *pVar = var; 

cout << var << endl; //this prints the value of var which is 5 

cout << &var << endl; //this should print the memory address of var 

cout << *&var << endl; //this should print the value at the memory address of var 

cout << *pVar << endl; //this should print the value in whatever the pointer is pointing to 

cout << &*var << endl; //I've heard that this would cancel the two out 

會發生什麼?我見過的通用語法:char* line = var;char * line = var;char *line = var;

+2

您是否嘗試過這一點? – aschepler

+0

相關(在C中:http://stackoverflow.com/a/30423656/335858) – dasblinkenlight

+0

在這個區域中,只有*空白符號用於區分令牌。例如,如果你有'char const * foo',你需要在'char'和'const'之間留空格(以防止它被視爲一個單獨的標記'charconst'),但其餘部分是無關緊要的 - 你可以根據需要在'*'的每一邊刪除或插入儘可能多的空白,並且它的含義也沒有區別(同樣用'&')。對於使用何種空白來最大化可讀性有廣泛的分歧。 –

回答

1

首先,int *pVar = var;不正確;這並不存儲var的地址,但它存儲的地址「5」,這將導致一個編譯錯誤說:

main.cpp: In function 'int main()': 
main.cpp:9:15: error: invalid conversion from 'int' to 'int*' [-fpermissive] 
    int *pVar = var; 
       ^~~ 

var需求是在*pvar初始化引用:

int *pVar = &var; 

其次cout << &*var << endl;也將導致在編譯錯誤,因爲var不是指針(int*)型變量:

main.cpp: In function 'int main()': 
    main.cpp:19:13: error: invalid type argument of unary '*' (have 'int') 
    cout << &*var << endl; //I've heard that this would cancel the two out 
       ^~~ 

現在,爲了回答你的問題時,引用(&)運算符和指針之間加空格(*)運營商將會對編譯器絕對沒有區別。唯一有所不同的是當你想分離2個令牌時;例如conststring。運行下面的代碼只是誇大的例子你問:

cout <<    &    var << endl; 
cout <<       *     & var << endl; 
cout <<         *pVar << endl; 

得到相同的結果,那些從代碼,而無需那麼多的空間:

0x7ffe243c3404 
5 
5 
相關問題