简体   繁体   English

C ++中的指针(语法)

[英]Pointer in C++ (syntax)

I have some guesses I wish to confirm. 我有一些想证实的猜测。 I would be extremely grateful if someone could help me out. 如果有人可以帮助我,我将不胜感激。

When I declare a pointer in C++, for example 例如,当我在C ++中声明一个指针时

int *x = 5;

Does that mean that * is not for dereferencing, but just for declaration of the pointer; 这是否意味着*不是用于取消引用,而是仅用于指针的声明; as a result, x is referring to the address of int x? 结果,x指向整数x的地址?

Thanks in advance. 提前致谢。

You are almost correct, int *x (that you can also write int* x ) means that x is a pointer to an int... But there is not int liked to it yet 您几乎是正确的, int *x (您也可以编写int* x )表示x是指向int的指针...但是还没有喜欢它的int

int *x = 5;

actually means that x is a pointer that is linked to memory address 5, which should contain an int. 实际上意味着x是链接到内存地址 5的指针,该地址应该包含一个int。 Since this address is probably not allocated by your program, this will likely fail. 由于此地址可能不是您的程序分配的,因此可能会失败。

You can try to do the following 您可以尝试执行以下操作

int x = 5;
int *xAddr = &x;
*xAddr = 3;

Here we declared xAddr in the same way as you did, but telling it that it points to the address (that's the & character) of x; 在这里,我们以与您相同的方式声明了xAddr,但告诉它它指向x的地址(即&字符)。 By changing the value that xAddr points to to 3 (line 3, here we are dereferencing), we change the value of x to 3 通过将xAddr指向的值更改为3(第3行,在此取消引用),我们将x的值更改为3

Here is a nice tutorial to understand pointers better 是一个很好的教程,可以更好地理解指针

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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