“衰减”是指表达式从数组类型到指针类型的隐式转换。在大多数情况下,当编译器看到一个数组表达式时,它会将表达式的类型从“T 的 N 元素数组”转换为“指向 T 的指针”,并将表达式的值设置为数组第一个元素的地址.此规则的例外情况是数组是 sizeof 或 & 运算符的操作数,或者数组是在声明中用作初始值设定项的字符串文字。
假设以下代码:
char a[80];
strcpy(a, "This is a test");
表达式a 的类型是“80 个字符的数组”,而表达式“这是一个测试”的类型是“15 个字符的数组”(在 C 中;在 C++ 中,字符串字面量是常量字符)。但是,在对strcpy() 的调用中,两个表达式都不是sizeof 或& 的操作数,因此它们的类型被隐式转换为“指向char 的指针”,并且它们的值被设置为第一个元素的地址每个。 strcpy() 接收的不是数组,而是指针,如其原型所示:
char *strcpy(char *dest, const char *src);
这与数组指针不同。例如:
char a[80];
char *ptr_to_first_element = a;
char (*ptr_to_array)[80] = &a;
ptr_to_first_element 和ptr_to_array 具有相同的值; a的基地址。但是,它们是不同的类型,不同的处理方式,如下所示:
a[i] == ptr_to_first_element[i] == (*ptr_to_array)[i] != *ptr_to_array[i] != ptr_to_array[i]
请记住,表达式a[i] 被解释为*(a+i)(仅当数组类型转换为指针类型时才有效),因此a[i] 和ptr_to_first_element[i] 的工作方式相同。表达式(*ptr_to_array)[i] 被解释为*(*a+i)。表达式*ptr_to_array[i] 和ptr_to_array[i] 可能会根据上下文导致编译器警告或错误;如果您期望他们评估为a[i],他们肯定会做错事。
sizeof a == sizeof *ptr_to_array == 80
同样,当数组是sizeof 的操作数时,它不会转换为指针类型。
sizeof *ptr_to_first_element == sizeof (char) == 1
sizeof ptr_to_first_element == sizeof (char *) == whatever the pointer size
is on your platform
ptr_to_first_element 是一个指向 char 的简单指针。