问题描述
限时送ChatGPT账号..在以下代码中,指针值和指针地址与预期不同.
In the following bit of code, pointer values and pointer addresses differ as expected.
但数组值和地址不是!
这怎么可能?
输出
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;
}
推荐答案
数组名通常取数组第一个元素的地址,所以array
和&array
具有相同的值(但类型不同,所以 array+1
和 &array+1
将 不 相等,如果数组长度超过 1 个元素).
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).
对此有两个例外:当数组名称是 sizeof
或一元 &
(address-of) 的操作数时,名称指的是数组对象本身.因此,sizeof array
为您提供整个数组的字节大小,而不是指针的大小.
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.
对于定义为T array[size]
的数组,其类型为T *
.当/如果你增加它,你会得到数组中的下一个元素.
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
计算为相同的地址,但给定相同的定义,它创建一个 T(*)[size]
类型的指针——即,它是指向数组的指针,而不是指向单个元素的指针.如果你增加这个指针,它会增加整个数组的大小,而不是单个元素的大小.例如,使用这样的代码:
&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));
我们可以期望第二个指针比第一个大 16 个(因为它是一个 16 个字符的数组).由于 %p 通常以十六进制转换指针,因此它可能看起来像:
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屋!
更多推荐
[db:关键词]
发布评论