'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



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zaman