简体   繁体   中英

little confusion regarding C++ pointers and this powerpoint slide

来自视频的图片,由ReelLearning提供

In the above powerpoint slide, why is it that:

int* p = &x; 
cout << *p << endl;

outputs 25? From the little understanding that I have with pointers, &x is the address of x, which is assigned to *p, the value of p. In that case, since &x is 0003, so shouldn't *p and its output also be 0003?

For all the advanced coders out there who cannot stand a simpleton like myself, I apologize in 'advance'.

&x is the address of x, which is assigned to *p

No, there is nothing assigned to *p . In that line p is defined with type int* and p is assigned the address of x .

Now p holds the address 0003 and *p holds 25.

The * only relates to the variable definition in that line. During initialization you assign values to the variable you define. If that wasn't the case, where should p point to in first place? Into which location should the 0003 be written then?

The slide is confusing, since it suggests that the name of the pointer variable were *p . The name of the variable is just p .

When you print the expression p , you will get 0003 , since that is the value of the pointer.

So the pointer points to the object at address 0003 , and the expression *p gets you the value from there, which is 25.

The slide should better say that cell 0001 has the name p . And that cell 0003 has two names (or paths to get there), which are x directly or *p indirectly.

When we declare pointer we use * with datatype for eg int *p it doesn't mean that we are declaring as well as referring to value at the same time.

So when you type int *p = &x; it is similar as writing

int *p;
p = &x;

Now p is 0003 and value at address 0003 is 25 . which you can get by *p .

引用运算符(&)引用变量x的地址,该变量分配给p 。由于p持有一个内存位置的地址,因此它是指针类型(int *) 。现在(* p),其中(* )是引用运算符(*)表示p中的地址所保存的值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM