c中的& a,& a [0],a有什么区别 [英] what is the difference between &a,&a[0],a in c
问题描述
我得到以下代码的输出-- 6
I got the output for the following code as -> 6
我对输出感到困惑,所以我更改了一小部分代码并进行了检查.
I was confused by the output, so I changed a small portion of code and checked it.
我将此 int * ptr =(int *)(a + 1)
替换为Not clear语句,我的输出为-> 1
.怎么样?
I substituted this int * ptr=(int*)(a+1)
for the Not clear statement, I got the output as --> 1
. How?
我听说& a
, a
, a [0]
都是相同的地址?是什么让它与众不同?
I heard &a
, a
, a[0]
all are same address? what makes it different?
#include<stdio.h>
int main()
{
int a[] = {1, 2, 3, 4, 5, 6};
int *ptr = (int*)(&a+1); //NOT CLEAR
printf("%d ", *(ptr-1) );
getchar();
return 0;
}
推荐答案
和许多其他开发人员一样,您对衰落感到困惑.以下代码是有效的,因为 a
将隐式地 decay 指向指针:
Like many other developers, you are confused by decay. The following code is valid, because a
will implicitly decay to a pointer:
int a[] = {1,2,3};
int* b = a;
衰减是值得注意的,它允许数组隐式转换为指向其第一个元素的指针.
Decay is what notably allows arrays to implicitly transform into pointers to their first elements.
但是,以下代码无效,因为衰减与获取数组的地址不同:
However, the following code is not valid, because decay is not the same as taking the address of the array:
int a[] = {1,2,3};
int* b = &a; // INVALID
第一个示例为您提供了一个指向整数(数组中的第一个整数)的指针.在第二个示例中,& a
为您提供指向3个整数的数组的指针.如果必须将其分配给变量,则其类型为:
The first example gets you a pointer to an integer (the first integer in the array). In the second example, &a
gets you a pointer to an array of 3 integers. If you had to assign it to a variable, its type would be:
int a[] = {1,2,3};
int (*b)[3] = &a;
外星人的形式应该告诉你,这根本不是你所期望的.
The alien form should show you that this is not what you expect at all.
a
(一旦衰减),& a
和& a [0]
确实都应该指向同一地址.但是,它们并不指向同一类型的事物(& a
指向数组,而其他指向整数).
It is true that a
(once decayed), &a
and &a[0]
should all point to the same address. However, they do not point to the same kind of thing (&a
points to an array, while the others point to integers).
指针操作的结果至少取决于指针的类型和指针的值.每次将& a
指针增加1时,您将在内存中移动三个整数,而不仅仅是移动一个,因为类型的大小为(3 *整数).这是您执行(& a + 1)
时发生的事情,这就是为什么您得到意外结果的原因.在此内存地址中未定义任何值,因此您会得到未定义的行为.
The result of pointer operations depend at least as much on the type of the pointer as to the value of the pointer. Each time you increase that &a
pointer by 1, you move by three integers in memory, not just one, because the size of the type is (3 * size of an integer). This is what happens when you do (&a + 1)
, and this is why you get an unexpected result. There is no value defined at this memory address, so you get undefined behavior.
它之所以编译是因为将指针强制转换为int指针,并且如果需要我的建议,则应该从不使有关强制转换指针的编译器警告保持沉默.
It compiles because you cast the pointer to an int pointer, and if you want my advice, you should never silence compiler warnings about pointers with casts.
这篇关于c中的& a,& a [0],a有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!