我尝试创建CD struct
,如:
typedef struct
{
char* nameCD;
int yearOfpublication;
song* listOfSongs;
int priceCD;
int numberOfSongs;
} CD;
我有一首歌struct
:
typedef struct
{
char* nameSong;
char* nameSinger;
int lenghtOfSong;
} song;
void SongInput(song *psong, CD *pcd)
{
pcd->numberOfSongs++;
pcd->listOfSongs = (song*)malloc(pmcd->numberOfSongs*sizeof(song));
// here all the code that update one song..
但我应该写什么来更新下一首歌?
如何将其更改为更新歌曲数量的数组以及如何保存所有歌曲?
我试过了:
printf("Enter lenght Of Song:");
scanf("%d", &psong->lenghtOfSong);
但我不明白指针.. 以及如何更新下一首歌?
}
void CDInput(CD *pcd)
{
int numberOfSongs = 0;
//here all the other update of cd.
//songs!!!!!!!!!!!!!!!!!!!!!!!!!!!!
pcd->numberOfSongs = 0;
pcd->listOfSongs = (song*)malloc(numberOfSongs*sizeof(song));
}
我还需要写其他什么吗?
答案 0 :(得分:2)
void CDInput(CD *pcd)
{
int i;
//...
printf("Enter number Of Song:");
scanf("%d", &pcd->numberOfSongs);
pcd->listOfSongs = (song*)malloc(pcd->numberOfSongs*sizeof(song));
for(i = 0; i < pcd->numberOfSongs; ++i){
SongInput(&pcd->listOfSongs[i]);
}
//...
}
答案 1 :(得分:1)
这取决于您是否要完全编写结构,或者您真的想要添加一个项目。
对于第一种情况,请参考BLUEPIXY's answer,对于第二种情况,请稍微复杂一些。
bool add_song(song *psong, CD *pcd)
{
song* newone = realloc(pcd->listOfSongs, (pmcd->numberOfSongs+1)*sizeof(song));
if (!newone) {
// return and complain; the old remains intact.
return false; // indicating failure.
}
// now we can assign back.
pcd->listOfSongs = newone;
newone[pcd->numberOfSongs++] = *psong;
return true; // indicating success.
}