如何减去地址引用?

问题描述 投票:0回答:2

我觉得z的值应该是40,因为a[5]有20个元素,它和a[4]之间的空间也有20个元素。然而z的实际值为2。

谁能解释这个概念? 任何帮助将不胜感激。

#include <stdio.h>

int main()
{
    int a[10][20];
    int z = &a[5] - &a[3];
    printf("%d\n", &a[3]); // the address infomation is 6421740
    printf("%d\n", &a[5]); // the address infomation is 6421900
    printf("%d\n", z); // z value is 2. why?
}
arrays c memory-address
2个回答
1
投票

指针运算以指向类型为单位进行。

在这种情况下,

a[5]
a[3]
都是
int [20]
类型数组的元素,并且
&a[5]
&a[3]
都具有
int(*)[20]
类型。它们相隔 2 个数组元素,所以它们之间的差异是 2.

底层类型也是数组也没关系


0
投票

它和a[4]之间的空间也有20个元素

不对,a[4]的

element
是20个
int
的数组类型。它不是一个整数。

它被称为指针算法。它不适用于 byteschars 仅适用于指针类型。

&a[3]
具有指向
int[20]
的指针类型。
&a[5]
具有指向
int[20]
的指针类型,它定位了来自
int[20]
.
 的两 (2) 个 
&a[3]

数组

用一个更简单的例子来解释就容易多了

int main(void)
{
    double dbl[10];
    for(size_t i = 0; i < 10; i++ )
    {
        size_t distance = (dbl + i) - dbl;
        size_t distancebytes = (char *)(dbl + i) - (char *)dbl;
        printf("dbl + %zu is %zu double and %zu bytes from dbl\n", i, distance, distancebytes);
    }
}
dbl + 0 is 0 double and 0 bytes from dbl
dbl + 1 is 1 double and 8 bytes from dbl
dbl + 2 is 2 double and 16 bytes from dbl
dbl + 3 is 3 double and 24 bytes from dbl
dbl + 4 is 4 double and 32 bytes from dbl
dbl + 5 is 5 double and 40 bytes from dbl
dbl + 6 is 6 double and 48 bytes from dbl
dbl + 7 is 7 double and 56 bytes from dbl
dbl + 8 is 8 double and 64 bytes from dbl
dbl + 9 is 9 double and 72 bytes from dbl

https://godbolt.org/z/KoKn8sM5b

© www.soinside.com 2019 - 2024. All rights reserved.