简体   繁体   English

使用 Malloc 动态分配结构

[英]dynamic allocation of struct with Malloc

Iam begginner in C and dynamic allocation, i would like to allocate a memory for a structure.我是 C 和动态分配的初学者,我想为结构分配一个 memory。 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 具有音乐标题列表,而签名者结构具有歌曲名称和他制作的专辑编号。

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?我的问题是,我需要为歌手结构的 nbrAlbum 分配 memory 吗? or it gonna be done with allocateSingerMusic function?还是用 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.并使用指针大小而不是结构大小分配 memory。

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.您的主要问题的答案是您需要为 nbrAlbum 分配 memory。 This is the power and beauty of C language that no dynamic memory will be allocated automatically unless it is done explicitly.这就是 C 语言的强大和美妙之处,除非明确完成,否则不会自动分配动态 memory。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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