Last active
August 29, 2015 14:23
-
-
Save cantbelievew/32258f0ac33facb2caec to your computer and use it in GitHub Desktop.
關於指標間加減運算
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "string.h" | |
#include "stdlib.h" | |
#include "stdio.h" | |
/* | |
20150608 關於指標間加減運算 | |
by CantBelieve W | |
*/ | |
int main(void) | |
{ | |
short *a, *b; | |
a = (short *)1; | |
b = (int *)1; | |
printf("%d %d %d %d %d\n", a, b ,a + (int)b, (int)(a + (int)b), (int)a + (int)b); | |
/* | |
a+(int)b = *a + sizeof(*a)*(*b) = 1 + 2*1 = 3 | |
(int)(a + (int)b) = (int)3 = 3 | |
(int)a + (int)b = 1 + 1 = 2 | |
*/ | |
a = (int *)0x5566; | |
b = (int *)0x5570; | |
printf("%d %d %d %d %d\n", a, b, (int)a+(int)b, a+(int)b, sizeof(int *)); | |
/* | |
a = 21862, b = 21872 (transfer base 16 to base 10) | |
(int)a+(int)b = 21862 + 21872 = 43734 | |
a+(int)b = *a + sizeof(*a)*b = 21862 + 2*21872 = 65606 | |
*/ | |
printf("%d\n", a - b); | |
printf("%d\n", ((int)b - (int)a)/sizeof(int *)); | |
/* | |
a - b = (21862 - 21872)/sizeof(*a) = -10/2 = -5 | |
(在這為一個 offset 的概念,意即-5為位移了5 bits,位址只能相減不能相加) <=重要! | |
((int)b - (int)a)/sizeof(int *) = 10/4 = 2 | |
*/ | |
a = (int*)0x1000; | |
b = a + 3; | |
printf("%d %d %p %p \n", a, b, a, b); | |
/* | |
a = 4096 | |
b = a + 3 = 4096 + 3*sizeof(*a) = 4096 + (3*2) = 4102 | |
*/ | |
system("pause"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment