首页 > 代码库 > a[2]地址-a[0]地址 实际等于 (a[2]地址-a[0]地址)/a的类型 -- C

a[2]地址-a[0]地址 实际等于 (a[2]地址-a[0]地址)/a的类型 -- C


#include <stdio.h>


int
main()
{
	int a[3] = {0x1,0x2,0x3};
	int *p, *q;
	
	printf("a[0] = 0x%X\n", a[0]);
	printf("a[1] = 0x%X\n", a[1]);
	printf("a[2] = 0x%X\n\n", a[2]);
	
	printf("&a[0] = 0x%X\n", &a[0]);
	printf("&a[1] = 0x%X\n", &a[1]);
	printf("&a[2] = 0x%X\n\n", &a[2]);

	p = &a[0];
	q = &a[2];
	printf("p = 0x%X\n", p);
	printf("q = 0x%X\n\n", q);

	/* q - p 实际运算是(q地址(0xBFE2097C) - p地址(0xBFE20984))/sizeof(int) */
	printf("q - p = 0x%X\n", q - p);
	printf("a[q - p] = 0x%X\n", a[q - p]);
	printf("a[&a[0] - &a[2]] = 0x%X\n", a[&a[2] - &a[0]]);
	
}
/*
[root@localhost test_class]# ./a.out 
a[0] = 0x1
a[1] = 0x2
a[2] = 0x3

&a[0] = 0xBFE2097C
&a[1] = 0xBFE20980
&a[2] = 0xBFE20984

p = 0xBFE2097C
q = 0xBFE20984

q - p = 0x2
a[q - p] = 0x3
a[&a[0] - &a[2]] = 0x3

*/