Re: [問題] 請問malloc的用法

看板Programming作者 (艾斯寇德)時間17年前 (2007/09/21 16:32), 編輯推噓1(101)
留言2則, 1人參與, 最新討論串2/2 (看更多)
※ 引述《ultrafire ()》之銘言: : int *ptr; : 1. ptr = malloc(sizeof(int*) * size); : 2. ptr = (int*)malloc(sizeof(int) * size); : 請問一下 : 這兩種用法在意義上或allocate出來的記憶體 : 有什麼差別呢? 沒差別 malloc只是發出一個訊號去syscall,跟作業系統要一塊記憶體 至於他是什麼型別,由指標來解釋 因為malloc原型 void* malloc(size_t blocksize); int* ptr = malloc(sizeof(int*)*size); int型別的指標 ptr 指向了一塊 sizeof(int*) * size 大小的區塊 這在c++上會說 不合法的轉換,從 void* 到 int* 而在純C的環境上這會給過 在C++至少應該要 int* ptr = (int*)malloc(sizeof(int*)*size) 而這邊會過,而且在blocksize跟你所想像的無誤的原因是 sizeof(int*) == 一個整數所佔有的大小 等同於 sizeof(int) 如果今天的型別不是int,而是double,甚至char 那麼這樣寫就會出錯 比如有一個比較大的型別 double* ptr = (double*)malloc(sizeof(double*) *size); 假使配置size : 16 頂多只有 8個可以用,因為double指標每次要位移 8 byte, 你期待配置 8 * 16 == 128 //sizeof(double)*size 但是你卻配置了 4 * 16 == 64 //sizeof(double*)*size int *ptr = (int*)malloc(sizeof(int)*size); 這在C++上才被視為正確的寫法 -- IceCold::IceCode -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.132.228.138 ※ 編輯: sunneo 來自: 220.132.228.138 (09/21 16:37)

09/21 16:59, , 1F
大部分同意,唯最後一句 C++ 建議使用
09/21 16:59, 1F

09/21 16:59, , 2F
static_cast<x>(y) 做轉型
09/21 16:59, 2F
文章代碼(AID): #16yu6huq (Programming)
文章代碼(AID): #16yu6huq (Programming)