....

2014年5月23日 星期五

[長知識] C語言 - 新手篇章 - 指標轉換應用

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {

int a=10, b=20, c=30;
int *ptr, *ptr_2;

ptr = &a;

printf("a的記憶體本身位置%i,指向的位置%i\n", &a, a);
printf("b的記憶體本身位置%d,指向的位置%d\n", &b, b);
printf("b的記憶體本身位置%d,指向的位置%d\n", &c, c);

//指標本身減2個單位(int = 4 byte),所以就是ptr退8個byte
//最後指標指到c的位置
ptr -=2;
printf("ptr的記憶體本身位置%d,指向的位置%d,內容%d\n", &ptr, ptr, *ptr);

//指標指到b的位置
ptr +=1;
printf("ptr的記憶體本身位置%d,指向的位置%d,內容%d\n", &ptr, ptr, *ptr);

//兩個指標指向同一個位置
ptr_2 = ptr;
printf("ptr的記憶體本身位置%d,指向的位置%d,內容%d\n", &ptr, ptr, *ptr);
printf("ptr_2的記憶體本身位置%d,指向的位置%d,內容%d\n", &ptr_2, ptr_2, *ptr_2);

return 0;

}

沒有留言:

張貼留言