Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

c - Address of array - difference between having an ampersand and no ampersand

I have a struct that looks like this:

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

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

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

Does anyone have a good explanation for this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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].

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).

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
", (void *) packet.data);
printf("%p
", (void *) &packet.data);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...