Learning C
Learning C

Reputation: 689

Having trouble allocating a structure array

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?

Upvotes: 1

Views: 152

Answers (2)

stefan bachert
stefan bachert

Reputation: 9624

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

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727137

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*.

Upvotes: 3

Related Questions