(short *)是什麼意思呢?
short *buf;
but = (short *)malloc(sizeof(short)*2000);
請問各位大大
1.(short *)是什麼意思呢?
2.(void *)是什麼意思?
3.為何sizeof(short *)和sizeof(short), 前者為4bytes 後者為2bytes呢
二者有什麼差別,一般都怎麼用,可否請大大舉例為佳?
看了好久,還不是太知道,是什麼意思,煩麻大大們幫忙"詳述"一下,謝謝^^
如果but = (short *)malloc(sizeof(short)*2000);去掉了(short *)會有什麼影響呢?
我懂了^^~
2 Answers
- 生鏽Lv 51 decade agoFavorite Answer
我先從指標講起,short *buf 表示一個有一個指標變數 buf 可以存放記憶體位址。在 WIN32 裡面,每一個記憶體位址需要 32 位元的空間才可以存放,所以無論式記錄哪一種型別的指標變數,它暫的大小都是 4 bytes。而每一個 short int 數值只占了兩個 byte (-32,768 ~ +32,767),這應該無疑義 (見 C 語言標準)。值得一提的是 int 的大小是與平台有關係的,它在 32 位元平台上是 32 位元,64 位元平台上是 64位元。這是 C 的原創者故意搞出來好讓程式能移植。
照理記憶體任何位置都可以寫成 void *,但標示成某一種特定型別 (如 short *) 是要讓指標與對應的資料型別能很容易的轉換。
既然已經提到 sizeof,我們不能不提 memory alignment。因為 CPU 的需求,物件與變數存放在記憶體位置一定要暫照某一種方式對齊。例如在 32 位元機器裡面,一個 4 bytes integer 存放在記憶體內的位址必須能被 4 整除。所以我們考慮下面的結構:
struct Employee
{
int ID;
char state[3];
int salary;
};
Employee 結構其實只需要 11 bytes (4+3+4) 就可以放所有資料,但是因為 int salary 的資料必須對齊 (能被 4 整除), sizeof(Employee) 會等於 12,也就是說,state 與 salary 中間有一個 byte 其實是沒有用的。
你的 malloc(sizeof(short)*2000); 表示要 allocate 2000 個可以存放 short int 資料的連續記憶體空間,假如是 malloc(sizeof(Employee)*2000); 表示要 allocate 2000 個可以存放 Employee 結構資料的連續記憶體空間。
malloc allocate 得到的記憶體型別是 void *,經過鑄型 (cast),把它轉為 short * 是一個好習慣,等於你告訴編譯器這就是你要的轉換,不加的話也可以,但有的編譯器會提出警告。
P.S. 依據 C standard,malloc 取得的記憶體通用於存放各種型別的資料:
The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated).
Source(s): http://www.devx.com/tips/Tip/13265Login to reply the answers
- HeresyLv 71 decade ago
short* 代表的是 short 的指標
void* 代表的是未知型別的指標
指標代表的是一個記憶體的位址,指到儲存數值的地方。
可以參考:http://libai.math.ncu.edu.tw/bcc16/C/C/b12-2.shtml
不論 char、int、float、double 這些基本資料型態的含量為何,它們衍生的指標資料型態的含量都一樣大。但是此大小卻與電腦硬體的設計有關。如今常見的所謂 32 位元電腦,其指標資料型態的含量是 4 (bytes),而所謂 64 位元電腦,其指標資料型態的含量通常是 8 (bytes)。
Login to reply the answers