地址(&)和间接运算符的正确格式是什么

时间:2017-04-08 00:48:03

标签: c++ pointers addressof

我已经看到了许多不同的编写地址运算符(&)和间接运算符(*)的方法

如果我没弄错的话应该是这样的:

//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

例如,如果您将&var写为& var并且两者之间有空格,会发生什么?我见过的常见语法:char* line = var;char * line = var;char *line = var;

1 个答案:

答案 0 :(得分:1)

首先int *pVar = var;不正确;这不存储var的地址,但它存储地址&#34; 5&#34;,这将导致编译错误说:

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