Question
please help me modify my c program by using a linked list to replace the array. also use malloc to do memory allocation. note that
please help me modify my c program by using a linked list to replace the array. also use malloc to do memory allocation. note that malloc does not support C++ strings
#include
#pragma warning(disable:4996)
//constants #define true 1 #define false 0
//prototypes bool getSongInfo(struct songInfo *song, char artist[], char title[]); void printSongInfo(struct songInfo songs[10]); void clearCR(char *buf);
//created structure called songInfo that has two fields with a pointer to a strings named artist and title struct songInfo { char *artist; char *title; };
//function called getSongInfo which gets the songs information bool getSongInfo(struct songInfo *song, char artist[], char title[]) { //allocates memory of size length of the string song->artist = (char *)malloc((strlen(artist) + 1) * sizeof(char)); if (song->artist == NULL) { printf("Out of memory "); return false; } //copies the artist name into our song element in array strcpy(song->artist, artist); song->title = (char *)malloc((strlen(title) + 1) * sizeof(char)); if (song->title == NULL) { printf("Out of memory "); return false; } //copies the title into our song element in array strcpy(song->title, title); }
//This function displays the songs and its title void printSongInfo(struct songInfo songs[10]) { //prints all the 10 songs information for (int i = 0; i<10; i++)
//40 is minimum number of chareters to be printed and '-' is to say they should be left justified printf("%-40s%-40s ", songs[i].artist, songs[i].title); }
int main() { struct songInfo songs[10]; char artist[40] = ""; char title[40] = "";
//loop and call getSongInfo for 10 times(10 pairs of songs) for (int i = 0; i<10; i++) { //get input from user printf("Enter the Name of the Artist for Song %d: ", i + 1); fgets(artist, sizeof(artist), stdin); clearCR(artist); if (sscanf(artist, "%d", &i) != 1) { printf("Enter the Title of Song %d: ", i + 1); } fgets(title, sizeof(title), stdin); clearCR(title); if (sscanf(title, "%d", &i) != 1) { printf(" "); } getSongInfo(songs + i, artist, title); } printSongInfo(songs); //free the memory for (int i = 0; i<10; i++) { free(songs[i].artist); free(songs[i].title); } return 0; }
void clearCR(char *buf) { char *whereCR = strchr(buf, ' '); if (whereCR != NULL) *whereCR = '\0'; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started