数组的地址 - 有一个符号和符号无区别 [英] Address of array - difference between having an ampersand and no ampersand

查看:143
本文介绍了数组的地址 - 有一个符号和符号无区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构,看起来像这样:

I have a struct that looks like this:

struct packet {
  int a;
  char data[500];
};
typedef struct packet packet_t;

我有点困惑,为什么下面的code输出相同的地址,每个printf的:

I'm a little confused why the following code outputs the same address for each printf:

void myfunction() {
  packet_t packet;
  printf("%p\n", packet.data);   //e.g., outputs 0x7fff1c323c9c
  printf("%p\n", &packet.data);  //e.g., outputs 0x7fff1c323c9c
}

有没有人有一个很好的解释这个?

Does anyone have a good explanation for this?

推荐答案

在大多数情况下,有输入 T N个元素的数组的前pression 将转换为类型的前pression指针 T ,其价值将是数组中的第一个元素的地址。这是第一个的printf 呼叫发生了什么;恩pression packet.data ,其类型为的char [500] ,替换为前$键入的char * ,其价值的对$ pssion是第一个元素的地址,所以你有效地打印&放大器; packet.data [ 0]

Under most circumstances, an expression that has type "N-element array of T" will be converted to an expression of type "pointer to T", and its value will be the address of the first element in the array. This is what happens in the first printf call; the expression packet.data, which has type char [500], is replaced with an expression of type char *, and its value is the address of the first element, so you're effectively printing &packet.data[0].

在数组前pression是一元&放的操作数发生的一个例外;恩pression类型&放大器; packet.data 字符(*)[500] (指针以500元的数组字符)。

One exception to this rule occurs when the array expression is an operand of the unary & operator; the type of the expression &packet.data is char (*)[500] (pointer to 500-element array of char).

数组的地址是一样的第一个元素的地址,所以这两个呼叫的printf 显示相同的的;这只是该类型前pressions是不同的。要学究,无论是前pressions应在的printf 通话被转换为无效* (即%p 转换说明需要一个无效* 参数):

The address of an array is the same as the address of the first element, so both calls to printf display the same value; it's just that the types of the expressions are different. To be pedantic, both expressions should be cast to void * in the printf calls (the %p conversion specifier expects a void * argument):

printf("%p\n", (void *) packet.data);
printf("%p\n", (void *) &packet.data);

这篇关于数组的地址 - 有一个符号和符号无区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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