简体   繁体   English

数组的地址是否等于它在 C 中的第一个元素

[英]Is the address of an array equal to its first element in C

Assume this array:假设这个数组:

int arr[5] = { 1, 2, 3, 4, 5 };

Here arr has two purpose - it is the name of the array and it acts as a pointer pointing towards the first element in the array, so arr is equal to &arr[0] by default.这里arr有两个用途——它是数组的名称,它充当指向数组中第一个元素的指针,因此默认情况下arr等于&arr[0]

My questions is, what about &arr ?我的问题是, &arr呢? is this also equal to the above?这也等于上面的吗?

An array is in fact an extent of memory.数组实际上是内存的一个范围。 So the address of an extent is the address of the stored array in this extent and of its first element.因此,范围的地址是该范围中存储的数组及其第一个元素的地址。

As a result an array designator used in expressions with rare exceptions is converted to pointer to its first element.因此,在具有罕见异常的表达式中使用的数组指示符被转换为指向其第一个元素的指针。

Using the example provided by you使用您提供的示例

int arr[5] = { 1, 2, 3, 4, 5 };

these expressions &arr and &arr[0] have the same value but are of different types.这些表达式&arr&arr[0]具有相同的值但类型不同。

The expression &arr has the type int( * )[5] while the expression &a[0] has the type int * .表达式&arr的类型为int( * )[5]而表达式&a[0]的类型为int *

Here is a demonstrative program.这是一个演示程序。

#include <stdio.h>

int main(void) 
{
    int arr[5] = { 1, 2, 3, 4, 5 };

    printf( "&arr == &arr[0] is %s\n", 
            ( void * )&arr == ( void * )&arr[0] ? "true" : "false" );

    printf( "sizeof( *&arr )  = %zu\n", sizeof( *&arr ) );          
    printf( "sizeof( *&arr[0] )  = %zu\n", sizeof( *&arr[0] ) );            
    return 0;
}

Its output is它的输出是

&arr == &arr[0] is true
sizeof( *&arr )  = 20
sizeof( *&arr[0] )  = 4

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

相关问题 为什么数组的地址等于它在 C 中的值? - How come an array's address is equal to its value in C? 为什么数组保存C中第一个元素的地址? - Why array holds the address of the first element in C? 在C中,数组第一个元素的地址和数组的地址一样吗? - In C, is the address of the first element in an array the same as the address of the array? 使用指向第一个元素的地址的指针打印数组 - Printing an array using a pointer which has the address to its first element 数组的第一个元素为何等于数组? - How come the first element of an array is equal to the array ?C 打印C中二维数组第一个元素的地址 - Printing the address of the first element of 2D array in C 是否可以在 C 中打印数组的第一个元素的内存地址? - Is it possible to printf the memory address of the first element of an array in C? 指向数组第一个元素的指针的地址? - Address of a pointer to first element of an array? C中的编译器如何获得数组第一个元素的地址和整个数组的地址之间的差异? - How can the compiler in C get the difference between the address of the first element of the array and the address of the whole array? 在C中,如何使该程序返回数组的地址而不是第一个元素的地址? - In C,how do I make this program return the address of an array,instead of address of first element?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM