首页 > 解决方案 > 尝试 printf() 不同的结构数组时出错

问题描述

我正在尝试打印出我的 struct songList[10] 的 10 个不同数组。我已经使用了调试器并确认请求的每个输入都正确存储在每个索引中,问题似乎出在我的打印功能中。我收到“在 mini1.exe 中的 0x0003187E 处引发的异常:0xC0000005:访问冲突读取位置 0xCCCCCCCC。” 尝试循环打印请求索引处的字符串时出错。任何帮助都会非常感谢!此外,我正在尝试从 songList[10] 数组的索引 0 开始打印每个 songArtist 和 songTitle。它应该打印左对齐并且每个都使用 35 个字符。

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#pragma warning(disable:4996)

int getSongInfo(struct songInfo *pFillInfo, char *artistName, char *songName);
int printSongInfo(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(songInfo *songList[])
{
    int counter = 0;

    while (counter != 10)
    {
        printf("%-35s", songList[counter]->songArtist);
        printf("%-35s\n", songList[counter]->songTitle);
        counter++;
    }

    return 1;
}

标签: carrayspointersstructprintf

解决方案


推荐阅读