获取数组变量的地址是什么意思? [英] What does getting the address of an array variable mean?

查看:80
本文介绍了获取数组变量的地址是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我读了一个C片段,这真的让我感到困惑:

Today I read a C snippet which really confused me:

#include <stdio.h>

int
main(void)
{
    int a[] = {0, 1, 2, 3};

    printf("%d\n", *(*(&a + 1) - 1));
    return 0;
}

我认为&a + 1没有任何意义,但它运行时没有错误.

In my opinion, &a + 1 makes no sense, but it runs without error.

是什么意思?并且 K& R C圣经涵盖了这一点吗?

What does it mean? And does the K&R C bible cover this?

更新0: 阅读答案后,我意识到这两个表达主要使我感到困惑:

UPDATE 0: After reading the answers, I realize that these two expressions mainly confuses me:

  1. &a + 1,已在StackOverflow上被问到:关于c

  1. &a + 1, which has been asked on Stack Overflow: about the expression "&anArray" in c

*(&a + 1) -1,与数组衰减有关.

推荐答案

我们来剖析它.

a具有类型int [4](4个整数的数组).它的大小是4 * sizeof(int).

a has type int [4] (array of 4 int). It's size is 4 * sizeof(int).

&a具有类型int (*)[4](指向4个int数组的指针).

&a has type int (*)[4] (pointer to array of 4 int).

(&a + 1)也具有类型int (*)[4].它指向一个由4个int组成的数组,该数组在a的开始之后开始1 * sizeof(a)个字节(或4 * sizeof(int)个字节).

(&a + 1) also has type int (*)[4]. It points to an array of 4 int that starts 1 * sizeof(a) bytes (or 4 * sizeof(int) bytes) after the start of a.

*(&a + 1)的类型为int [4](4个int数组).它的存储开始是1 * sizeof(a)个字节(或a开始后的4 * sizeof(int)个字节).

*(&a + 1) is of type int [4] (an array of 4 int). It's storage starts 1 * sizeof(a) bytes (or 4 * sizeof(int) bytes after the start of a.

*(&a + 1) - 1的类型为int *(指向int的指针),因为数组*(&a + 1)会衰减为指向此表达式中第一个元素的指针.它将指向一个以*(&a + 1)字节开头的int字符.这是与&a[3]相同的指针值.

*(&a + 1) - 1 is of type int * (pointer to int) because the array *(&a + 1) decays to a pointer to its first element in this expression. It will point to an int that starts 1 * sizeof(int) bytes before the start of *(&a + 1). This is the same pointer value as &a[3].

*(*(&a + 1) - 1)的类型为int.因为*(&a + 1) - 1是与&a[3]相同的指针值,所以*(*(&a + 1) - 1)等效于已初始化为3a[3],因此这是printf打印的数字.

*(*(&a + 1) - 1) is of type int. Because *(&a + 1) - 1 is the same pointer value as &a[3], *(*(&a + 1) - 1) is equivalent to a[3], which has been initialized to 3, so that is the number printed by the printf.

这篇关于获取数组变量的地址是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆