文章程式碼顯示

2018年12月11日 星期二

《筆記》C語言 - 補充_5:char* 指到一個 int 變數? 指針強制轉型的作用?

程式碼

#include 
#include 

int main(void) {
 char nCHAR = 'A';
 int nINT = 305419896; //(0x12345678)
 char* pCHAR = NULL;
 int* pINT = NULL;

 printf("nCHAR = %c (0x%x) \n", nCHAR, nCHAR);
 printf("nINT = %d (0x%x) \n\n", nINT, nINT);

 printf("nCHAR's address = %p\n",&nCHAR);
 printf("nINT's address = %p\n\n",&nINT);

 printf("pCHAR = %d \n", pCHAR);
 printf("pINT = %d  \n\n", pINT);

 printf("pCHAR's address = %p\n",&pCHAR);
 printf("pINT's address = %p\n\n",&pINT);

 pCHAR = &nCHAR;
 pINT = &nINT;

 printf("== 將pCHAR指向nCHAR,將pINT指向INT ==\n");
 printf("pCHAR = 0x%x \n", pCHAR);
 printf("pINT = 0x%x  \n\n", pINT);
 printf("-- 間接取值 --\n");
 printf("nCHAR = %c (0x%x) \n", *pCHAR,*pCHAR);
 printf("nINT = %d (0x%x)  \n\n", *pINT, *pINT);

 printf("== char* pUSE ==\n");
 char* pUSE = NULL;
 pUSE = &nCHAR;
 printf("pUSE = 0x%x\n", pUSE);
 printf("pCHAR by (char*)pUSE = 0x%x \n", *pUSE);
 printf("-- 如果把 char* 指向一個 int 變數 !? --\n");
 pUSE = &nINT;
 printf("pUSE = 0x%x\n", pUSE);
 printf("nINT by (char*)pUSE = 0x%x \n", *pUSE);
 printf("-- 指針位移 --\n");
 pUSE = pUSE + 1;
 printf("pUSE+1 = 0x%x\n", pUSE);
 printf("nINT by (char*)pUSE+1 = 0x%x \n", *pUSE);
 printf("-- 指針粗暴強制轉型 --\n");
 pUSE = &nINT;
 printf("pUSE = 0x%x\n", pUSE);
 printf("nINT by (int*)pUSE = 0x%x \n",  *((int*)pUSE));

 return EXIT_SUCCESS;
}





我的 Youtube 頻道,一定要訂閱
我將定期推出程式語言的新手教學影片


↓↓↓ 連結到部落格方針與索引 ↓↓↓

Blog 使用方針與索引