My project requires me to allocate memory dynamically. What am I doing wrong?
/*Setting up my Struture*/
struct album_ {
int num_tracks;
struct tracks_ tracks;
int playlist_hits[];
};
typedef struct album_ album;
/*Try to allocate memory for structure*/
fscanf(album_file,"%d", &number_of_album);
album *all_albums_p = (album *)malloc(sizeof(album)*number_of_album);
for(i=0;i < number_of_album; i++){
all_albums_p[i].num_tracks = (int *)malloc(sizeof(int));
all_albums_p[i].num_tracks = i+1;
printf("%d\n",all_albums_p[i].num_tracks);
}
Error Message
warning: assignment makes integer from pointer without a cast [enabled by default]
Also if I wanted to return this array is it correct to return all_albums_p
?
This line
all_albums_p[i].num_tracks = (int *)malloc(sizeof(int));
should be
all_albums_p[i].playlist_hits = (int *)malloc(sizeof(int));
Since you are allocating an array of album
, you need to replace the flexible array member with a pointer: playlist_hits
should be changed to int*
.
The complaining line is
all_albums_p[i].num_tracks = (int *)malloc(sizeof(int));
you assign a pointer to an int to it. That will cause a memory leak. I have no idea what you intend with that
This line is also strange
all_albums_p[i].num_tracks = i+1;
you have n album and you say the number of tracks will be depend on the index of the album. This is very unlikely.
the first album has 1 track.
The thousandth album has 1000 tracks.
does not sound very rational
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.