首页 > 解决方案 > C中另一个结构内的结构数组

问题描述

我浏览了所有类似的问题,但它们要么太具体,要么与我手头的问题不够相关。

我将尝试使其尽可能通用。

问题:我有一个“播放列表”结构和一个“歌曲”结构。我的“播放列表”结构的元素之一是一组歌曲。我希望能够硬编码 X 首歌曲并将它们附加到 Playlist 结构中的歌曲数组中。

这是我的代码:

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

typedef struct Song {
    int id;
    char *artist;
    float duration;
    char *album;
} Song;

struct Playlist {
    char *name;
    int id;
    char *author;
    struct Songs *songs;
};

int main(int argc, char const *argv[])
{
    struct Playlist spotify;
    spotify.name = "Your Top Songs 2019";
    spotify.id = 1;
    spotify.author = "Spotify";
    spotify.songs = malloc(5 * sizeof(struct Song));
    Song s;
    s.id = 1;
    spotify.songs[0] = s;
    return 0;
}

当我尝试编译它时,我收到以下错误:

test.c:27:18: error: subscript of pointer to incomplete type 'struct Songs'
    spotify.songs[0] = s;
    ~~~~~~~~~~~~~^
test.c:15:12: note: forward declaration of 'struct Songs'
    struct Songs *songs;
           ^
1 error generated.

我不确定这意味着什么或如何解决它。任何指导将不胜感激。

标签: cstruct

解决方案


struct Songs *songs;forward 声明了一个名为 的结构Songs,它保持为一个不完整的类型。你的意思可能是struct Song *songs;.


推荐阅读