Learning C
Learning C

Reputation: 689

How to point one structure to another

I need help pointing *user_playlist to a playlist node. How can I do this?

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

struct users_ {
  int user_ID;
  playlists *user_playlist;
  struct users_ *next;
};
typedef struct users_ users;

p_users = (users *)malloc(sizeof(users *));
p_users -> user_ID = account_number;
head_users = p_users;
head_users -> next = NULL;
users_pointer = head_users;

p_playlists = (playlists *)malloc(sizeof(playlists));
curr_playlists = p_playlists;
curr_playlists -> album = NULL;
curr_playlists -> track_num = NULL;
curr_playlists -> next = NULL;
curr_users -> user_playlist = curr_playlists;

 users *head_users,*curr_users,*p_users,*users_pointer;
 playlists *head_playlists,*curr_playlists,*p_playlists,*playlist_pointer;

Upvotes: 1

Views: 1022

Answers (1)

hmjd
hmjd

Reputation: 121961

This is a problem:

p_users = (users *)malloc(sizeof(users *));

it only allocates the size of a pointer, not the size of a users structure. Change to:

p_users = malloc(sizeof(users));

or:

p_users = malloc(sizeof(*p_users));

Casting the return value of malloc() is unnecessary and potentially dangerous.

EDIT:

Dereferencing an unitialised, or NULL, pointer will cause a segmentation fault. This declares but does not initialise curr_users (same for other variables listed):

users *head_users,*curr_users,*p_users,*users_pointer;

An attempt is then made to access curr_users:

curr_users->user_playlist = curr_playlists; /* Segmentation fault. */

Initialise curr_users before using, to either a valid users structure or to NULL and check for non-null before deferencing:

users *head_users = NULL,*curr_users = NULL,
    *p_users = NULL,*users_pointer = NULL;

if (curr_users)
{
    curr_users->user_playlist = curr_playlists;
}

Upvotes: 4

Related Questions