我需要帮助将*user_playlist
指向播放列表节点。我怎么能这样做?
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;
答案 0 :(得分:4)
这是一个问题:
p_users = (users *)malloc(sizeof(users *));
它只分配指针的大小,而不是users
结构的大小。改为:
p_users = malloc(sizeof(users));
或:
p_users = malloc(sizeof(*p_users));
Casting the return value of malloc()
is unnecessary and potentially dangerous.
编辑:
取消引用unitialised或NULL
指针将导致分段错误。这声明但不初始化 curr_users
(对于列出的其他变量也是如此):
users *head_users,*curr_users,*p_users,*users_pointer;
然后尝试访问curr_users
:
curr_users->user_playlist = curr_playlists; /* Segmentation fault. */
在使用之前初始化curr_users
,有效users
结构或NULL
并在引用之前检查非null:
users *head_users = NULL,*curr_users = NULL,
*p_users = NULL,*users_pointer = NULL;
if (curr_users)
{
curr_users->user_playlist = curr_playlists;
}