Использование strcpy () для копирования строки в структуру, когда память выделяется с помощью malloc () - PullRequest
0 голосов
/ 16 мая 2019

В настоящее время в моей программе пользователь вводит название песни и название исполнителя для некоторых песен. Каждая строка хранится в массиве. Затем я пытаюсь использовать эти введенные строки в функции для выделения памяти с помощью 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;
}
...