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?

2
  • 3
    Standard Warning : Please do not cast the return value of malloc(). Commented Dec 29, 2014 at 7:48
  • 1
    and, you need to use realloc() to resize the memory and add the new value to it. Commented Dec 29, 2014 at 7:50

2 Answers 2

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]);
    }
    //...
}
Sign up to request clarification or add additional context in comments.

3 Comments

a little bit of explanation wouldn't hurt :-/ code-only answers sucks.
I respect the original. It is not a mistake.
Answer is subjective, respectively.
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.
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.