Currently in my program I have the user enter both a Song Title, and Artist Title for some songs. Each string is stored in an array. I am then trying to use those entered strings in a function to allocate memory by using malloc(), then use strcopy to copy the strings into a multi dimensional array variable of my struct. I've copied the code below. I keep getting a "Exception thrown: write access violation." error when my function uses malloc, and cant seem to figure out why. Any help would be appreciated. It is expected that the strings will be no more than than a size of 30, and there will be 10 arrays of the struct variable to store 10 different songs with their artist.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#pragma warning(disable:4996)
int getSongInfo(struct songInfo *pFillInfo, char *artistName, char *songName);
int printSongInfo(struct songInfo *songList[]);
struct songInfo {
char *songArtist;
char *songTitle;
};
int main(void)
{
struct songInfo *fillPtr, songList[10];
fillPtr = &songList[0];
char tempArtist[30][10];
char tempSong[30][10];
int i = 0;
int counter = 0;
int arrayCounter = 0;
while (counter != 10)
{
printf("Please enter the artist name: ");
fgets(tempArtist[counter], sizeof(tempArtist[counter]), stdin);
printf("Please enter the song name: ");
fgets(tempSong[counter], sizeof(tempSong[counter]), stdin);
getSongInfo(&fillPtr[arrayCounter], tempArtist[counter], tempSong[counter]);
printf("Song and Artist Captured! \n");
counter++;
arrayCounter++;
}
printSongInfo(&fillPtr);
}
int getSongInfo(struct songInfo *pFillInfo, char *artistName, char *songName)
{
pFillInfo->songArtist = (char*)malloc(strlen(artistName) + 1);
pFillInfo->songTitle = (char*)malloc(strlen(songName) + 1);
strcpy(pFillInfo->songArtist, artistName);
strcpy(pFillInfo->songTitle, songName);
return 1;
}
int printSongInfo(struct songInfo *songList[])
{
int counter = 0;
while (counter != 10)
{
printf("%-35s%-35s", &songList[counter]->songArtist, &songList[counter]->songTitle);
counter++;
}
return 1;
}