简体   繁体   中英

dynamic allocation of struct with Malloc

Iam begginner in C and dynamic allocation, i would like to allocate a memory for a structure. struct MusicTitle has the list of a music title and the signer structure has the name of the songs and number of album that he made.

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
}

my question is, do i need to allocate memory for nbrAlbum of the singer structure? or it gonna be done with allocateSingerMusic function? Thank you

There are few syntax and logical problems with this code. For example Missing semicolon.

musicTitle* musicTitleofsigner

and allocating memory with size of pointer rather than size of struct.

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

I hope, you will correct those mistakes. Answer to your main question is that you need to allocate memory for nbrAlbum. This is the power and beauty of C language that no dynamic memory will be allocated automatically unless it is done explicitly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM