看板 NCTU-STAT98G 關於我們 聯絡資訊
#include <stdio.h> #include <stdlib.h> #include <math.h> int main() { double y=0.1; double *w; /* 將變數宣告為指標變數(pointer variable):抓記憶體前不需要加& 下面介紹三種指標變數三種記憶體宣告方式 */ w = &y; /* Type 1 指標常數宣告: 將指標變數的記憶體指向一個已經宣告的指標常數 ex: w = &y; 此時可由以下發現w與y的記憶體位置相同 此種宣告, 一次只能指向"一個"指標常數 */ printf("Memory Address of w = %x\n",w);//a. 不需要加& printf("Memory Address of w = %x\n",&w[0]);//b. 需要加& printf("Memory Address of w = %x\n",&*w);//c. 等同b 需要加& printf("Memory Address of y = %x\n",&y);//d. 需要加& /* 將w宣告為指標變數後, w[0]代表第一個值, 其值所在記憶體位址在w 所以抓記憶體位址有三種方式: 第一種:%x 配合w 第二種:%x 配合&w[0] 第三種:%x 配合&*w (這邊w[0],*w皆是表示值所以要用&) (也就是a. b. c是同樣顯示結果的三種不同寫法) 問題:如果宣告為維度2以上的向量w[0],w[1],...,分別為其值 那麼如何抓位址? 這邊先想想 答案下面有 */ system("pause"); printf("The old value of w = %lf\n",w[0]); printf("The old value of y = %lf\n",y); w[0] = 0.2; printf("The new value of w = %lf\n",w[0]); printf("The new value of y = %lf\n",y); /* 因為y與w共用同個記憶體位置, 所以不管y或者w改變值, 兩者同時改變 PS: w已經宣告為向量, 要從w[0]抓值 */ system("pause"); w = (double *) 0x12ff34; /* Type 2 直接給位址: 直接分配一個8 bytes (相對於double)的記憶體給指標變數 可以從下面從印出來的數字可以看到記憶體的初始位址與所佔空間 */ printf("Memory Address of w = %x\n",w); printf("Memory Address of some variable next to w = %x\n",w+1); system("pause"); w = (double *) malloc(2*sizeof(double)); /* Type 3 系統分配一組位址: (double *): 代表資料形態指標宣告 malloc: Memory Allocated,記憶體配置 malloc(個數*資料形態所佔的長度): 決定配置記憶體空間大小 */ printf("Memory Address of w = %x\n",w); printf("Memory Address of w = %x\n",w+1); /* 宣告w具有2個指標變數分別為w, w+1,其值為w[0],w[1] 上兩個printf結果等同下列: */ printf("Memory Address of w = %x\n",&w[0]); printf("Memory Address of w = %x\n",&w[1]); /* 或者 */ printf("Memory Address of w = %x\n",&*w); printf("Memory Address of w = %x\n",&*w+1); return 0; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.113.7.248