为什么一个数组的地址等于它在C值? [英] How come an array's address is equal to its value in C?
问题描述
在code以下位指针值和指针地址不同预期。
但是数组值和地址都没有!
怎么能这样呢?
输出
my_array = 0022FF00
&安培; my_array = 0022FF00
pointer_to_array = 0022FF00
&安培; pointer_to_array = 0022FEFC
的#include<&stdio.h中GT;诠释的main()
{
焦炭my_array [100] =一些很酷的字符串;
的printf(my_array =%P \\ N,my_array);
的printf(&安培; my_array =%P \\ N,&安培; my_array); 字符* pointer_to_array = my_array;
的printf(pointer_to_array =%P \\ N,pointer_to_array);
的printf(&安培; pointer_to_array =%P \\ N,&安培; pointer_to_array); 的printf(preSS ENTER继续... \\ n);
的getchar();
返回0;
}
数组的名称通常计算结果为数组的第一个元素的地址,所以阵列
和&放大器;阵列
值相同(但不同类型,所以阵列+ 1
和 &安培;阵列+ 1
将的不的相等,如果数组超过1元长)
有两个例外:当数组名是的sizeof的操作数
或一元&安培;
( )-的地址,名称指的是数组对象本身。因此,的sizeof阵列
让你在整个阵列,而不是一个指针的大小的字节数。
有关定义为 T数组[大小]数组
,它将有键入 T *
。当/如果你增加它,你到数组中的下一个元素。
&放大器;阵列
评估为同一地址,但由于相同的定义,它创建的类型 T(*)[大小的指针]
- 也就是说,它是一个指向数组的指针,而不是一个单一的元素。如果您增加此指针,它会添加整个数组的大小,单个元素而不是规模。例如,code是这样的:
字符数组[16];
的printf(%P \\ T%P(无效*)及阵列(无效*)(安培;阵+ 1));
我们可以预期的第二指针以大于第一16(因为它的16字符的数组)。自从%P通常以十六进制转换的指针,它可能看起来像:
0x12341000 0x12341010
In the following bit of code, pointer values and pointer addresses differ as expected.
But array values and addresses don't!
How can this be?
Output
my_array = 0022FF00
&my_array = 0022FF00
pointer_to_array = 0022FF00
&pointer_to_array = 0022FEFC
#include <stdio.h>
int main()
{
char my_array[100] = "some cool string";
printf("my_array = %p\n", my_array);
printf("&my_array = %p\n", &my_array);
char *pointer_to_array = my_array;
printf("pointer_to_array = %p\n", pointer_to_array);
printf("&pointer_to_array = %p\n", &pointer_to_array);
printf("Press ENTER to continue...\n");
getchar();
return 0;
}
The name of an array usually evaluates to the address of the first element of the array, so array
and &array
have the same value (but different types, so array+1
and &array+1
will not be equal if the array is more than 1 element long).
There are two exceptions to this: when the array name is an operand of sizeof
or unary &
(address-of), the name refers to the array object itself. Thus sizeof array
gives you the size in bytes of the entire array, not the size of a pointer.
For an array defined as T array[size]
, it will have type T *
. When/if you increment it, you get to the next element in the array.
&array
evaluates to the same address, but given the same definition, it creates a pointer of the type T(*)[size]
-- i.e., it's a pointer to an array, not to a single element. If you increment this pointer, it'll add the size of the entire array, not the size of a single element. For example, with code like this:
char array[16];
printf("%p\t%p", (void*)&array, (void*)(&array+1));
We can expect the second pointer to be 16 greater than the first (because it's an array of 16 char's). Since %p typically converts pointers in hexadecimal, it might look something like:
0x12341000 0x12341010
这篇关于为什么一个数组的地址等于它在C值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!