c - 尝试 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;
}
解决方案
推荐阅读
- keycloak - 如何创建自定义 Keycloak 主题?
- sql - 创建表 - Oracle APEX 错误:是什么导致了我的 CREATE TABLE sql 脚本中的错误?
- node.js - CastError 与 GET 端点但不是与 Express / Mongoose 中的 POST 端点?
- r - 基于以 R 结尾的元素分组
- .net-core - 错误解组数据'\''寻找值 Ghz 到 gRPC 的开头
- python - 如何处理 Pandas 中的缺失值
- javascript - Trix 编辑器将段落格式扩展到相邻段落
- c# - C# 与 Devexpress 框架
- python-3.x - 我如何从输入中分解一个单词并将其应用于键的打印功能:已建立字典的值对
- php - 获取字符串中两个标签之间的所有内容