指针一个链表到另一个链表

时间:2012-04-03 22:58:29

标签: c pointers linked-list structure

我试图将一个结构中的指针指向另一个结构的节点。我现在已经坚持了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;

2 个答案:

答案 0 :(得分:2)

人们已经给出了答案,但我想我会更完整地提出一个建议:

为了最大限度地减少混淆,确保您做到正确,并在发生某些变更时尽量减少维护工作,请始终使用malloc,如下所示:

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

请注意,在这种情况下,type的{​​{1}}仅提及一次。如果更改,则无需触及其余代码。此外,pointer始终正确显示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

答案 1 :(得分:1)

错误似乎在这一行:

p_playlists = malloc(sizeof(playlists *));

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

p_playlists = malloc(sizeof(playlists));

playlist_结构分配足够的内存。

修改
如下面的评论所示,您还需要在curr_users块中为else分配内容。然后,除非你的程序中的任何其他错误,它应该工作:)