C 指向数组的指针——我无法向自己解释的事情

标签 c arrays pointers

<分区>

有人可以解释以下行为吗?这让我怀疑。

这是我的一个非常简单的程序

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/

相关文章:

c - 在 Linux 中禁用磁盘缓存

c - 在带链表的递归函数中使用 rand()

c++ - 指向 const 重载成员函数的指针

java - 如何分析 native JNI 库

c - 限制有限状态自动机字符串匹配的字母表

javascript - 在javascript中将数组本身合并到另一个具有相同键的数组中

将字符串连接到指针变量的末尾

pointers - 从克隆方法返回托管指针

C 程序在轨道数组中搜索轨道

java - 数组随机问题