3

I have tried to create a CD struct like :

typedef struct
{
  char* nameCD;
  int yearOfpublication;
  song* listOfSongs;
  int priceCD;
  int numberOfSongs;
} CD;

and I have a song 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..

but what should I write to update the next song?

how do I change it into an array which update the number of the songs and how can I save all the songs?

I tried this :

printf("Enter lenght Of Song:");

scanf("%d", &psong->lenghtOfSong);

but I don't understand the pointers.. and how to update the next song?

}

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));
} 

Do I need to write anything else?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

2 Answers2

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]);
    }
    //...
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
1

It depends on if you want to write the structure once completely or you really want to add one item.

For the first case, please refer to BLUEPIXY's answer, for the second one, thigs are slightly more complicated.

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.
}
Community
  • 1
  • 1
glglgl
  • 89,107
  • 13
  • 149
  • 217