C programming code #define MAX_LEN 80 typedef struct {char *title; int duration;
ID: 3806828 • Letter: C
Question
C programming code #define MAX_LEN 80 typedef struct {char *title; int duration;} Song typedef struct {Song* all_songs;/* array of songs*/int number_of_songs; char album_name [MAX_LEN + 1];} Album a. Given two Song structures s1 and s2, are there any problems with assigning one structure to another? Is deep copying taking place during the assignment of these two structures? b. Define a function that initializes a song using a duration and a string provided. The function will make a copy of the string parameter. c. Define a function that will initialize an Album structure based on an array of Songs provided as parameter. The function will create a dynamically-allocated array of Songs and will initialize each entry with a copy of the corresponding song in the parameter array. Feel free to add to the function any parameters you understand are needed.Explanation / Answer
HI, Please find my implementation.
Please let me know in case of any issue.
a)
Yes, assignment is supported for structs.
However, there are problems here:
Sonf struct contain a pointer variable: title
Now the pointers of both structs point to the same block of memory - the compiler does not copy the pointed to data. It is now difficult to know which struct instance owns the data.
b)
struct Song *createSong(char *title, int d){
struct Song *song = (struct Song *)malloc(sizeof(struct Song));
song->title = (char *)malloc(sizeof(char)*strlen(title));
strcpy(song->title, title);
song->duration = d;
return song;
}
c)
struct Album *createAlbum(struct Song songs[], int size, char *album_name){
struct Album *album = (struct Album *)malloc(sizeof(struct Album));
album->all_songs = (struct Song *)malloc(sizeof(struct Song)*size);
int i;
for(i=0; i<size; i++){
album->all_songs[i] = createSong(song[i].title, songs[i].duration);
}
album->number_of_songs = size;
strcpy(album->album_name, album_name);
return album;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.