简体   繁体   English

分配结构数组时遇到问题

[英]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 ? 另外如果我想返回这个数组是否正确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* . 由于您要分配一个album数组,因此需要使用指针替换灵活数组成员: playlist_hits应更改为int*

The complaining line is 抱怨线是

all_albums_p[i].num_tracks = (int *)malloc(sizeof(int));

you assign a pointer to an int to it. 你为它指定一个int指针。 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. 你有n张专辑,你说曲目的数量将取决于专辑的索引。 This is very unlikely. 这是不太可能的。

the first album has 1 track. 第一张专辑有1首曲目。

The thousandth album has 1000 tracks. 第1000张专辑有1000首曲目。

does not sound very rational 听起来不太合理

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM