我需要帮助将*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;
这是一个问题:
p_users = (users *)malloc(sizeof(users *));
它只分配指针的大小而不分配users
结构的大小。更改为:
p_users = malloc(sizeof(users));
或:
p_users = malloc(sizeof(*p_users));
铸造malloc()
的返回值是不必要的,并且具有潜在的危险性。
编辑:
取消引用统一指针或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
,并在延迟前检查是否为非空:
users *head_users = NULL,*curr_users = NULL,
*p_users = NULL,*users_pointer = NULL;
if (curr_users)
{
curr_users->user_playlist = curr_playlists;
}