数组名称和数组名称的地址如何打印相同的值? [英] How can array name and the address of the array name both prints the same value?

查看:88
本文介绍了数组名称和数组名称的地址如何打印相同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码片段.

int main(){
    int x[2];
    x[0]=100;
    x[1]=200;
    printf("%d\n",x);
    printf("%d\n",&x);
    printf("%d\n",*x);
}   

输出为(三行)

6487616  6487616 100

我读到数组名称是指向数组第一个元素的指针.因此,'x' 的值打印了一个内存地址.但是,如果我尝试打印保存数组第一个元素地址的指针的地址,为什么还会打印相同的内存地址?难道它不应该打印另一个内存地址,仅仅是因为为了让变量存储内存地址,它应该是一个指针,并且该指针变量在 RAM 中也有一个内存地址.

I've read that the array name is a pointer to the first element of the array. Therefore, the value of 'x' prints a memory address. But if i try to print the address of the pointer which holds the address of the first element of the array, why does that also print the same memory address? Shouldn't it be printing another memory address, simply because in order for a variable to store a memory address it should be a pointer and that pointer variable also has a memory address in the RAM.

int main(){
   int y = 10;
   int *p = &y;

   printf("%d\n",&y);
   printf("%d\n",&p);   
}

上面的代码给出的输出为

The above code gives the output as

6487628 6487616

那么为什么这对数组不起作用?

So why doesn't this work when it comes to arrays?

推荐答案

与您可能听说的相反,数组和指针不是一回事.数组是给定类型的一个或多个元素的序列,而指针指向内存位置(可能是数组的第一个元素).因此,数组的地址与第一个元素的地址相同.

Contrary to what you might have heard, arrays and pointers are not the same thing. An array is a sequence of one or more elements of a given type, while a pointer points to a memory location (which may be the first element of an array). Because of this, the address of an array is the same as the address of the first element.

令人困惑的地方在于,在大多数表达式中,数组衰减成为指向第一个元素的指针.这种衰减不会发生的时间之一是当数组是地址运算符 & 的主题时.

Where the confusion comes in is that in most expressions, an array decays into a pointer to the first element. One of the times this decaying does not happen is when the array is the subject of the address-of operator &.

在您的第一段代码中,您首先打印 x.暂时忽略您应该使用 %p 打印指针而不是 %d,这里 x 衰减为指向第一个的指针元素,该地址就是打印的内容.在下一次调用 printf 时,传入 &x.这与 x 具有相同的值(当转换为指针时)但具有不同的类型,即 x 具有类型 int [2] (它衰减为 int *) 并且 &x 具有类型 int (*)[2].

In your first piece of code, you first print x. Ignoring for the moment that you should be using %p to print a pointer instead of %d, here x decays into a pointer to the first element and that address is what is printed. In the next call to printf, you pass in &x. This has the same value as x (when converted to a pointer) but has a different type, i.e. x has type int [2] (which decays to int *) and &x has type int (*)[2].

在你的第二个例子中,y 是一个 intp 是一个 int *.这些是单独的变量,因此每个变量都有不同的地址.

In your second example, y is an int and p is an int *. These are separate variables, so each has a different address.

这篇关于数组名称和数组名称的地址如何打印相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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