0

我试图将一个结构中的指针指向另一个结构的节点。我已经被困在这10个小时了。有人可以帮我修复我的代码吗?我在curr_users -> playlist = p_playlists;. 我指错了吗?

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

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

int transaction(FILE *transaction_file,album *all_album){
  int transaction_id,i;
  int album_ID,
      account_number,
      add_playlist_user,
      add_playlist_album,
      add_playlist_track;

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

  head_users = NULL;

  fscanf(transaction_file,"%d\n",&account_number);

  /*Checks for empty list, if true creates the first user*/
  if( !(head_users)){
    p_users = malloc(sizeof(users ));
    p_users -> user_ID = account_number;
    head_users = p_users;
    head_users -> next = NULL;
    users_pointer = head_users;

  /*If list is not empty create new user and puts it in front of list*/
  }else{
    p_users = malloc(sizeof(users));
    p_users -> user_ID = account_number;
    curr_users = p_users;
    curr_users -> next = head_users;
    head_users = curr_users;
    users_pointer = head_users;
    }
  /*Create an empty playlist for user and set everything to null*/

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

运行此代码时收到的错误消息:

Program received signal SIGSEGV, Segmentation fault.
0x00011050 in transaction (transaction_file=0xff3675cc, all_album=0x226b0)
    at functions.c:94
94            curr_users -> playlist = p_playlists;
4

2 回答 2

2

人们已经给出了答案,但我想我会通过一个建议让它更完整:

为了尽量减少混乱,确保你做对了,并在某些更改的情况下尽量减少维护工作,请始终malloc像这样使用:

type *pointer = malloc(count * sizeof(*pointer));

请注意,在这种情况下,typeofpointer只被提及一次。如果它发生变化,您无需接触其余代码。此外,sizeof(*pointer)始终正确显示可以存在于pointer.


现在回到您的代码,您是否注意到您有以下局部变量:

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

未初始化,您正在检查

if( !(head_users))

? 既然你的评论说if list is empty, create the first user,我猜你需要的是全局化,或者在程序启动时将它head_users传递给transaction并初始化它。NULL

于 2012-04-03T23:09:18.190 回答
1

错误似乎在这一行:

p_playlists = malloc(sizeof(playlists *));

您为指向playlist_结构的指针分配了足够的内存,而没有为整个playlist_结构分配足够的内存。将行更改为:

p_playlists = malloc(sizeof(playlists));

playlist_结构分配足够的内存。

编辑
如下面的评论所示,您还需要curr_userselse块中分配一些东西。然后,除非您的程序中出现任何其他错误,否则它应该可以工作:)

于 2012-04-03T23:05:35.417 回答