[問題] malloc的問題
各位強者大家好,以下有兩段程式碼,都可以順利執行rum-time無錯誤:
第一段:
struct ns{
int data;
};
void allocation(struct ns **temp){
//*temp位址印出為b7711000
*temp=(struct ns *)malloc(sizeof(struct ns ));
//*temp位址印出為8a4c008
}
int main(){
struct ns *temp;
//temp位址印出為b7711000
allocation(&temp);
//temp位址印出為8a4c008
temp->data=5;
}
--------------------------------------------------------------------
第二段:
struct ns{
int data;
};
void allocation(struct ns *temp){
//temp位址印出為b76ce000
temp=(struct ns *)malloc(sizeof(struct ns ));
//temp位址印出為9313008
}
int main(){
struct ns *temp;
//temp位址印出為b76ce000
allocation(temp);
//temp位址印出為b76ce000
temp->data=5;
}
以上兩段程式碼皆為分配記憶體空間,使得temp->data=5可以執行,
小弟想請問的是,第一段程式碼是將&temp傳入,也就是將temp本身的位址傳入allocation,
第二段則是把尚未分配空間的指標temp傳入allocation,
為何都可以讓temp->data=5順利執行呢?
我在面試的時候寫的是第二段程式碼,面試官說不可能過,第一段程式碼是他心中的答案,
但我回家試了之後發現似乎皆可,不知其中意義差別為何,會有何影響呢? 謝謝!
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.44.28.73
推
11/25 13:46, , 1F
11/25 13:46, 1F
→
11/25 13:48, , 2F
11/25 13:48, 2F
※ 編輯: jwliang 來自: 114.44.28.73 (11/25 13:55)
→
11/25 13:56, , 3F
11/25 13:56, 3F
→
11/25 13:57, , 4F
11/25 13:57, 4F
→
11/25 13:59, , 5F
11/25 13:59, 5F
→
11/25 14:14, , 6F
11/25 14:14, 6F
討論串 (同標題文章)
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章