Pointers with structures in structures c

I 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 can I change it to an array that updates the number of songs and how can I store all songs?

I've tried this:

printf("Enter lenght Of Song:");

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

      

but I don't understand 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?

+3


source to share


2 answers


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]);
    }
    //...
}

      



+2


source


It depends if you want to write the entire structure or if you want to add one element.

In the first case, see BLUEPIXY's answer , for the second, a little 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.
}

      

+1


source







All Articles