当前,在我的程序中,我让用户输入一些歌曲的“歌曲标题”和“艺术家标题”。每个字符串都存储在一个数组中。然后,我尝试在函数中使用这些输入的字符串通过使用malloc()分配内存,然后使用strcopy将字符串复制到结构的多维数组变量中。我已经复制了下面的代码。我不断收到“抛出异常:写访问冲突”的消息。我的函数使用malloc时出错,并且似乎无法弄清原因。任何帮助,将不胜感激。预计这些字符串的大小将不超过30,并且将有10个struct变量数组,用于与其艺术家一起存储10首不同的歌曲。
#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;
}