<分区>
有人可以解释以下行为吗?这让我怀疑。
这是我的一个非常简单的程序
int main () {
char str[50];
int len;
printf( "str %p, pstr %p\n", str, &str );
return(0);
}
这是程序的输出
str 0x7ffd864f1990, pstr 0x7ffd864f1990
到底为什么指针值完全一样?
提前致谢
<分区>
有人可以解释以下行为吗?这让我怀疑。
这是我的一个非常简单的程序
int main () {
char str[50];
int len;
printf( "str %p, pstr %p\n", str, &str );
return(0);
}
这是程序的输出
str 0x7ffd864f1990, pstr 0x7ffd864f1990
到底为什么指针值完全一样?
提前致谢
最佳答案
这是因为数组退化为指针。
在大多数情况下,当使用数组名称时,它会衰减为指向数组第一个元素的指针。这就是将 str
传递给 printf
时发生的情况。这种衰减不会发生的少数情况之一是当数组是寻址运算符&
的主题时。这给出了数组本身的地址,它与第一个元素的地址具有相同的值。这就是打印值相同的原因。
此转换在 C 标准的第 6.3.2.1 节中有详细说明:
3 Except when it is the operand of the
sizeof
operator, the_Alignof
operator, or the unary&
operator, or is a string literal used to initialize an array, an expression that has type "array of type" is converted to an expression with type "pointer to type" that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.
虽然两个表达式的类型不同(一个是char *
,一个是char (*)[50]
) , 两个指针的值相同。
关于C 指向数组的指针——我无法向自己解释的事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50857881/