[英]Pointers in C and C++
I am exploring a concept of Pointers in C and C++.我正在探索 C 和 C++ 中指针的概念。 I have already read so many articles about it but still I have got some doubts.
我已经阅读了很多关于它的文章,但我仍然有一些疑问。 Looking forward that anyone of you can clear them.
期待你们中的任何人都可以清除它们。
So Here's my questions:所以这是我的问题:
Declared Single Dimensional array like this:像这样声明一维数组:
int array[5] = {1, 2, 3, 4, 5};
Now I am printing below values:现在我正在打印以下值:
printf("array--->%u", array); // Output: 3199709072
printf("&array--->%u", &array); // Output: 3199709072
printf("*array--->%d", *array); // Output: 1
printf("*&array--->%d", *&array); // Output: 3199709072
First three output are same as what I expected but I dont understand the fourth one.前三个输出与我预期的相同,但我不明白第四个。
Why is it printing an address of first element of array??为什么要打印数组第一个元素的地址?
I am using *&array
expression that means I am explicitly specifying that I want value at &array
address but still it prints address of first element.我正在使用
*&array
表达式,这意味着我明确指定我想要&array
地址处的值,但它仍然打印第一个元素的地址。
Any ideas??有任何想法吗??
When unary *
and unary &
comes together they nullify each others effect.当一元
*
和一元&
结合在一起时,它们会抵消彼此的效果。 *&array
is equivalent to array
. *&array
等价于array
。 Since arrays decays to pointer to its first element when passed as an argument to a function, array
will give address of the first element of the array array
.由于数组在作为参数传递给函数时衰减为指向其第一个元素的指针,因此
array
将给出数组array
的第一个元素的地址。
Looking it another way, the expression *&array
will be parsed as (* (&array) )
;换个角度看,表达式
*&array
将被解析为(* (&array) )
; retrieve the address of array array
and then dereference it.检索数组
array
的地址,然后取消引用它。 Since &array
is an address of an array, dereferencing it will give back the array itself, but as per the rule the dereferenced array will decay to pointer to its first element and it will make the expression *&array
equivalent to array
.由于
&array
是&array
的地址,取消引用它会返回数组本身,但根据规则,取消引用的数组将衰减为指向其第一个元素的指针,并且它将使表达式*&array
等效于array
。
NOTE: Use %p
specifier to print address.注意:使用
%p
说明符打印地址。 Like像
printf("array--->%p", (void *)array);
Otherwise, using wrong specifier will invoke undefined behavior.否则,使用错误的说明符将调用未定义的行为。
Use the %p instead instead to get the pointer address in memory.改用 %p 来获取内存中的指针地址。 Your code will generate undefined behaviors.
您的代码将生成未定义的行为。 Simply use the following example.
只需使用以下示例。
printf("%p \n",pointer);
//where pointer is array in your case
That should do.那应该做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.