对数组元素的地址进行减法时出现意外结果
Unexpected result when doing subtraction of addresses of array elements
我在基于 x32 的处理器上 char = 1 byte, short = 2 bytes and int = 4 bytes
。
当我创建一个类型为 char
且其中包含 20
元素的数组时,我希望看到分配给该数组的 20 个内存空间,地址仅相差 1 byte
因为数组的类型。
如果我从数组中取出两个连续的元素并减去它们的地址,在这种情况下我不应该得到 1
吗?
对于类型为 short
和 int
的数组,我希望得到 2
和 4
。这是因为 short
和 int
元素需要在内存中对齐。 short elements
将在偶数地址(diff 2)上并且 int elements
将在可被 4 整除的地址上。
不过,为什么当我 运行 以下代码时我得到 1,1,1
而不是 1,2,4
?
我怀疑我在指针运算方面遗漏了一些关键细节。
char vecc[20];
printf("%i\n", &vecc[1]-&vecc[0]);
short vecs[20];
printf("%i\n", &vecs[1]-&vecs[0]);
int veci[20];
printf("%i\n", &veci[1]-&veci[0]);
指针减法产生的结果是索引的差异,而不是地址之间的间隙大小。
引用 C11
,第 6.5.6 章,(强调我的)
When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements. [...]
如果你这样写代码:
printf("%i\n", (char*)(&vecs[1]) - (char*)(&vecs[0]));
printf("%i\n", (char*)(&veci[1]) - (char*)(&veci[0]));
输出将是 2 和 4。
我在基于 x32 的处理器上 char = 1 byte, short = 2 bytes and int = 4 bytes
。
当我创建一个类型为 char
且其中包含 20
元素的数组时,我希望看到分配给该数组的 20 个内存空间,地址仅相差 1 byte
因为数组的类型。
如果我从数组中取出两个连续的元素并减去它们的地址,在这种情况下我不应该得到 1
吗?
对于类型为 short
和 int
的数组,我希望得到 2
和 4
。这是因为 short
和 int
元素需要在内存中对齐。 short elements
将在偶数地址(diff 2)上并且 int elements
将在可被 4 整除的地址上。
不过,为什么当我 运行 以下代码时我得到 1,1,1
而不是 1,2,4
?
我怀疑我在指针运算方面遗漏了一些关键细节。
char vecc[20];
printf("%i\n", &vecc[1]-&vecc[0]);
short vecs[20];
printf("%i\n", &vecs[1]-&vecs[0]);
int veci[20];
printf("%i\n", &veci[1]-&veci[0]);
指针减法产生的结果是索引的差异,而不是地址之间的间隙大小。
引用 C11
,第 6.5.6 章,(强调我的)
When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements. [...]
如果你这样写代码:
printf("%i\n", (char*)(&vecs[1]) - (char*)(&vecs[0]));
printf("%i\n", (char*)(&veci[1]) - (char*)(&veci[0]));
输出将是 2 和 4。