2

Will p = (users *)malloc(sizeof(users)); create memory for the playlist structure too? Also how can I reference playlist.album using p?

struct playlist_ {
  int album;
  int track_num;
  struct playlist_ *next;
};

struct users_ {
  int user_ID;
  struct playlist_ playlist;
  struct users_ *next;
};

typedef struct playlist_  playlists;
typedef struct users_ users;

users *p;
p = (users *)malloc(sizeof(users));
Learning C
  • 679
  • 10
  • 27
  • http://stackoverflow.com/questions/4982339/malloc-of-struct-array-with-varying-size-structs Not your question, but has some good examples. –  Apr 02 '12 at 20:04

2 Answers2

5

Will p = (users *)malloc(sizeof(users)); create memory for the playlist structure too?

playlist is a member of users_, so it forms part of the allocated space. So to answer your question: yes.

[Incidentally, you don't need to (and shouldn't) cast the result of malloc.]

Also how can I reference playlist.album using p?

Depends what you mean by "reference". Assuming you just mean "access", then this:

p->playlist.album
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
0

Yes it will. struct users_ contains an instance of struct playlist_ so allocating memory for the former will reserve room for the latter too.

On the other hand, if struct users_ contained a pointer to struct playlist_ you'd have to allocate memory for the latter after allocating memory for the former.

To reference playlist.album use p->playlist.album

Praetorian
  • 106,671
  • 19
  • 240
  • 328