This question already has answers here:
What are the barriers to understanding pointers and what can be done to overcome them? [closed]
                                
                                    (28个答案)
                                
                        
                                5年前关闭。
            
                    
int num1 = 8;   //okay
int *pointer;   //okay
*pointer = &num1;   //NOT okay, compiler says (Error:a value of type int* cannot be
                    //assigned to an entity of type "int")

int num2 = 8;   //okay
int *pointer = &num2;   //okay


我很困惑为什么第一部分给出错误而第二部分没有给出错误,它们在我看来是相同的

最佳答案

在赋值语句中:

*pointer = &num1;   //NOT okay


*pointerpointer指向的值,类型为int&num1num1的地址,类型为int*。正如编译器所说,您不能将指针分配给整数。

pointer = &num1*pointer = num1都可以,取决于您是要修改指针本身还是指向指针的值。

在声明中:

int *pointer = &num2;   //okay


尽管外观与赋值语句相似,但这会初始化pointer而不是*pointer。它声明pointer为指针,其类型与int*相同。

关于c++ - C++指针声明和赋值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24777782/

10-15 16:06