关于C语言中的数组名称和数组地址 [英] About array names and addresses of arrays in C

查看:140
本文介绍了关于C语言中的数组名称和数组地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

#include<stdio.h>

void main()
{
    int * a;
    int arr[2];
    arr[1] = 213 ;
    arr[0] = 333 ;
    a = &arr ;
    printf("\narr %d",arr);
    printf("\n*arr %d",*arr);
    printf("\n&arr %d",&arr);

    printf("\n%d",a[1]);
}

在运行此简单程序时,我得到的输出如下:

On running this simple program i get the output as follows :

arr -1079451516
*arr 333
&arr -1079451516
213

为什么arr和& arr都给出相同的结果?我可以理解arr是某个内存位置,而* arr或arr [0]是存储在该位置的值,但是为什么& arr和arr相同?

Why is it that both arr and &arr give the same result ? I can understand that arr is some memory location and *arr or arr[0] is the value stored at the position, but why is &arr and arr same ?

推荐答案

几乎每次使用数组类型的表达式时,它都会立即衰减"到第一个元素的指针. arr成为类型为int*的指针,而该指针实际上是传递给printf的指针. &arr是类型为int (*)[2]的指针(指向两个int的数组的指针).这两个指针的地址相同,因为它们都指向数组的开头.

Almost any time you use an expression with array type, it immediately "decays" to a pointer to the first element. arr becomes a pointer with type int*, and this pointer is what's actually passed to printf. &arr is a pointer with type int (*)[2] (pointer to array of two ints). The two pointers have the same address, since they both point at the beginning of the array.

(数组到指针转换的一个显着例外是sizeof自变量.)

(One notable exception to the array-to-pointer conversion is in a sizeof argument.)

这篇关于关于C语言中的数组名称和数组地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆