c - 访问结构内数组中的数据时出错

标签 c arrays struct

我正在尝试制作一个程序,以便为学校作业制作播放列表。

为了做到这一点,我为歌曲和艺术家制作了结构:

struct song {
    int id;     /* unique identity of the song                      */
    char name[40];      /* name of song                             */
    int duration;       /* duration in seconds                          */
    artist* artist;     /* pointer to artist                            */
};

struct artist {
    int id;     /* unique identity of artist                        */
    char name[30];      /* name of artist (could be a band as well)             */
    song* songList;     /* pointer to array containing all songs from this artist   */
    int amountSongs;
};

然后,我从文件中读出相关信息,以便获取所有歌曲和所有艺术家的指针数组。

这一切都有效。

然后我尝试创建一个播放列表,我要求用户输入他想要添加到播放列表中的歌曲的 ID,并为此检索指向该歌曲的正确指针:

printf("Type the ID of the song that you want to add\n");
int inputID;
scanf("%i", &inputID);

for(i=0;i<(*numberOfSongs);i++){
    if (inputID==((*song_ptr)+i)->id){
        printf("Song is found!!!!!\n\n");

        songArray  = realloc((songArray ), ((numberSongsInPlaylist) + 1) * sizeof(struct song));
        struct song *next = songArray  + (numberSongsInPlaylist);
        next = ((*song_ptr)+i);
        numberSongsInPlaylist++;

        printf("%i  \n", next->id);
        printf("%i  \n", (*songArray[0]).id);
    }
}

如您所见,我在这里打印了 ID 号。 既适用于当前添加的歌曲,也适用于歌曲数组中的第一首歌曲。 (用于调试) 这就是问题所在。

第一个打印 next->id 打印正确的值,第二个打印似乎是一个地址。

我尝试了一些方法,但都不起作用,我希望这里有人可以帮助我解决这个问题,以下是我尝试过的方法:

printf("%i  \n", (**songArray[0]).id);     //invalid type unary '*' //does not compile
printf("%i  \n", &(*songArray[0]).id);     //Prints address (I think, value changes with each run)
printf("%i  \n", (*songArray).id);         //Error: request for member 'id' in something not a structure or union
printf("%i  \n", (*songArray)->id);        //Prints address

欢迎任何帮助。

此后,我尝试将此歌曲数组添加到具有 ID、此歌曲数组及其中歌曲数量的播放列表结构中。

我在以下代码中执行此操作,并打印播放列表中的值:

*playlist_ptr  = realloc((*playlist_ptr ), ((*numberOfPlaylists) + 1) * sizeof(struct playlist));
struct playlist *nextPlay = *playlist_ptr  + (*numberOfPlaylists);

nextPlay->id = numberOfPlaylists;
nextPlay->numberOfSongs = numberSongsInPlaylist;
nextPlay->songs = songArray;
printf("song ID %d\n\n", ((*playlist_ptr) + 0)->songs[0]->id);

这将打印与第二条打印语句相同的值。这让我想知道问题是否出在songArray中数据的存储上,但是我找不到错误。

<小时/>

[评论更新]

它[songArray]实际上被声明为struct Song **songArray = NULL;

最佳答案

你真的把这件事搞得太复杂了。我假设 songArray 被声明为 struct Song* SongArray?在这种情况下,songArray[0] 返回一个 struct Song,而不是 struct Song*。在这种情况下,您只需要 songArray[0].id

关于c - 访问结构内数组中的数据时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27212372/

相关文章:

C getline内存泄漏不同的行为

java - 关于我的数组代码

c++ - 空指针代替 int 类型的指针

go - for循环初始化器中的结构

c - 两部分 : SPIKE fuzzer: "undefined symbol: s_word"

c - 在 C 中,bool( boolean 值)占用多少空间?是 1 位、1 字节还是其他?

c - 找到大小为 k 的子集,使得值之间的最小距离最大

c - 这两种具有结构的 typedef 实现是否等效?

go - 将变量传递给结构函数

c - 从对象的高级定义生成 C 结构