Understanding the interpretation of array labels

53 Views Asked by At

The following program demonstrates a somewhat surprising fact that many people may not be aware of.

#include <stdio.h>

void test(char[]);

int main(void) {
  char array[] = {0};
  printf("[Control]  (&array[0]: %p)\n", &array[0]);
  printf("[Local]    (array: %p) (&array: %p)\n", array, &array);
  test(array);
}

void test(char array[]) {
  printf("[Function] (array: %p) (&array: %p)\n", array, &array);
}

Compilation:

gcc -o test test.c && ./test

Output:

[Control]  (&array[0]: 0x5b49a21cf4e6)
[Local]    (array: 0x5b49a21cf4e6) (&array: 0x5b49a21cf4e6)
[Function] (array: 0x5b49a21cf4e6) (&array: 0x63f81d8e4950)

The label for an array is apparently treated differently depending on whether it is the name of a variable passed to a function versus when it is referring to a local variable. In the case of the locally declared array, the expressions "array", "&array", and "&array[0]" yield precisely identical addresses. Whereas within a function the label does not resolve the same way.

Why is that?

0

There are 0 best solutions below