jeudi 13 août 2015

return dynamic array of struct from function

How do I dynamically create an array of struct in a function in C?

The struct:

typedef struct Track {
    char artist[LONGSTR];
    char file[LONGSTR];
    int id;
    int isAlbum;
    char name[LONGSTR];
    int pos;
    char title[LONGSTR];
    int time;
} Track;

The function:

int
processplaylist (struct Track** tracks, char* resp)
{
  //count the tracks to return
  //allocate space for the resulting tracks

  *tracks = mem_alloc (count * sizeof (struct Track));

  //process each track
  return count;
}

And the usage:

char playliststr[] = "file: some-mp3\nTitle: Dire Straits - Romeo And Juliet\nName: TheRadio\nPos: 0\nId: 12\nOK\n"
struct Track* tracks = NULL;
int count = mpd_processplaylist(&tracks, playliststr);

Within the function the tracks are nicely processed and upto the return statement tracks points to the right location to get to the tracks. Most questions I have seen are about arrays to values, not structs. This answer returns an array of structs, but I would like to return the count (question of style) and return the array through the parameter.

What is going wrong? After the function returns, count has the right value and tracks is still NULL.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire