簡體   English   中英

使用 Malloc 動態分配結構

[英]dynamic allocation of struct with Malloc

我是 C 和動態分配的初學者,我想為結構分配一個 memory。 struct MusicTitle 具有音樂標題列表,而簽名者結構具有歌曲名稱和他制作的專輯編號。

struct musicTitle()        // structure of music title
{
Char* nameofsong;
char* Singer_name;
Char * release_year; }


musicTitle* allocteMusicTitle(){ // function to allocate memory for the music title struct
musicTitle* musicTitlePtr= (musicTitle*)malloc(sizeof(musicTitle*));
return musicTitlePtr;
}

struct singer{      // each singer has musictitle and albums
musicTitle* musicTitleofsigner
int* nbrAlbum;
}

singerMusic* allocateSingerMusic {
singerMusic* singerMusicPtr= (singerMusic*)malloc(sizeof(singerMusic*)); //allocate memory for singerMusic struct
}

我的問題是,我需要為歌手結構的 nbrAlbum 分配 memory 嗎? 還是用 allocateSingerMusic function 來完成? 謝謝

這段代碼幾乎沒有語法和邏輯問題。 例如缺少分號。

musicTitle* musicTitleofsigner

並使用指針大小而不是結構大小分配 memory。

singerMusic* singerMusicPtr= (singerMusic*)malloc(sizeof(singerMusic*));

我希望,你會改正這些錯誤。 您的主要問題的答案是您需要為 nbrAlbum 分配 memory。 這就是 C 語言的強大和美妙之處,除非明確完成,否則不會自動分配動態 memory。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM