如何从其他结构访问结构数组?我想从all_albums_p访问track_titles。我tried all_albums_p[i] -> all_tracks_p[j].tracks_title
但它给了我一个错误
struct tracks_{
char *tracks_title;
int playlist_hits;
};
struct album_ {
int num_tracks;
struct tracks_ tracks;
};
typedef struct album_ album;
typedef struct tracks_ tracks;
album *all_albums_p = (album *)malloc(sizeof(album)*number_of_album);
fscanf(album_file,"%d", &all_albums_p[j].num_tracks);
tracks *all_tracks_p = (tracks *)malloc(sizeof(tracks)*all_albums_p[j].num_tracks);
for(i=0;i<all_albums_p[j].num_tracks;i++){
fscanf(album_file,"%d", &number_of_charaters);
all_tracks_p[i].tracks_title = (char *)malloc(sizeof(char)*(number_of_charaters+1));
fscanf(album_file, "%[^\n]s", all_tracks_p[i].tracks_title);
printf("%s\n",all_tracks_p[i].tracks_title);
all_tracks_p[i].playlist_hits = 0;
}
/*These is where it is giving me errors*/
for(i=0; i < 10 ;i++){
printf("%d : %d\n",i,all_tracks_ptr[i].num_tracks);
for(j=0; j < number_of_albums[i].num_tracks ;j++){
printf("%s", number_of_albums[i]->all_tracks[j].tracks_title)
}
}
编译器说:
project3.c:26:39: error: request for member 'num_tracks' in something not a structure or union
project3.c:27:34: error: invalid type argument of '->' (have 'int')
答案 0 :(得分:2)
正如您现在声明的那样,每张专辑只关联一首曲目。我相信你想要为每个项目声明多个轨道,所以你应该把它作为指针类型
struct album_ {
int num_tracks;
struct tracks_* tracks;
};
一旦你做完了,那么拥有一个all_tracks
变量并没有多大意义。曲目与专辑相关联,因此您希望在每个专辑中分配曲目而不是全局。由于这是作业,我不想给出确切的答案,但诀窍是一次初始化一个专辑,并将曲目作为一组添加到每个专辑。