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

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

最佳答案

首先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

关于c++ - 地址 (&) 和间接运算符的正确格式是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43289009/

相关文章:

c++ - linux 到 windows C++ 字节数组

c - 指向结构的指针的大小

c++ - 设置 vector of int 指针,指向 int vector 的元素

c - 正在释放的指针未分配!无法解决

c - 为什么仅使用此 C 程序的参数列表中声明的指针即可通过引用传递?

c++ - 为什么someNumber = rand()&100 + 1;不会产生错误?

c++ - 即使设置为 PTHREAD_PROCESS_SHARED,Pthread 条件变量也不会发出信号

c++ - 如何在 C++ 中生成 overflow_error 或 underflow_error 异常?

Java/C++ : possible to have common code for multiple cases in switch?

c++ - 变量参数列表 : use va_list or address of formal parameter?