c - 指向数组的指针究竟是如何工作的?

标签 c arrays pointers

谁能解释这些值将如何打印以及为什么 p 和 *p 返回相同的值。

#include <stdio.h>

int main(){
    int arr[] = {1,2,3,4};
    int (*p)[4];

    p = &arr;

    printf("%u %u %u %u %u", arr, &p, p, *p, **p);
    p++;
    printf("\n%u %u %u %u %u", arr, &p, p, *p, **p);

    return 0;
}

我的机器输出如下:

2686768 2686764 2686768 2686768 1

2686768 2686764 2686784 2686784 2686792

最佳答案

你的例子很乱,但指针运算通常很乱,对类型不尊重。从类型理论的角度来看,你的例子没有意义。

arr 指向数组的第一个元素。请注意,arr[i] 等同于 *(arr+i)arrint 类型的 4 元素数组。

p 是指向 int 类型的 4 元素数组的指针。

你把&arr的地址赋值给p,它和arr的地址相同(只是类型不同,见下文) .

然后你打印出来,这意味着:

  • arr是数组首元素的地址
  • &pp
  • 的地址
  • p&arr的地址(整个数组),也就是arr的地址,也就是第一个元素的地址在数组中
  • *parr的地址,也就是数组第一个元素的地址
  • **p 正在尝试取消引用 *p,这是取消引用 arr,它实际上是数组的第一个元素<

在你递增p++之后:arr&p不会改变,其余的会改变


来自C Book

We have already emphasized that in most cases, the name of an array is converted into the address of its first element; one notable exception being when it is the operand of sizeof, which is essential if the stuff to do with malloc is to work. Another case is when an array name is the operand of the & address-of operator. Here, it is converted into the address of the whole array. What's the difference? Even if you think that addresses would be in some way ‘the same’, the critical difference is that they have different types. For an array of n elements of type T, then the address of the first element has type ‘pointer to T’; the address of the whole array has type ‘pointer to array of n elements of type T’; clearly very different. Here's an example of it:

int ar[10];
int *ip;
int (*ar10i)[10];       /* pointer to array of 10 ints */

ip = ar;                /* address of first element */
ip = &ar[0];            /* address of first element */
ar10i = &ar;            /* address of whole array */

关于c - 指向数组的指针究竟是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31047644/

相关文章:

python - 从 python 脚本调用 gcc 给我 'Undefined symbols: "_main"

c - 将文件中的 ASCII 字符读入数组

javascript - KO/JS : Refreshing an array by only pushing new values and keeping existing ones

c - 局部变量的地址是否总是保证有效

c - 字符串 C 中的整数之和

C 宏对于 gcc 和 MS Visual Studio 的工作方式不同

c - 有没有可以运行 C 文件的 C 编译器?

objective-c - 使用 for..in 逐行读取文件

android - 将来自服务器的数据放入字符串数组

无法读取由 malloc 创建的字符串