2

我一直在尝试创建一个专辑目录,其中链表上的每个节点都有一个索引(代码)、艺术家姓名和专辑名称。然而,由于某种原因,每次我尝试打印列表时,它都会显示我为每个节点分配的正确索引,但是对于每个项目,显示的艺术家和风格将是我为非常最后一个节点。也就是说,如果我为一个节点输入了“1,Oasis 和 Definetely_Maybe”,为第二个节点输入了“5,Aerosmith and Pump”,当我运行 print_list 时,它会显示

Code: 1

Artist: Aerosmith

Album: Pump

Code: 5

Artist: Aerosmith

Album: Pump

不知何故,它用最后一个覆盖了第一个节点的艺术家和专辑名称。无论我在结束运行之前输入多少个节点,它都会发生。

我知道这是非常新手,但我才刚刚开始编程,非常感谢您的帮助。代码如下。非常感谢。

 #include <stdio.h>
    #include <stdlib.h>
    #define MAX 100

    typedef struct n {int code; char *artist; char *album; struct n* next;} Node;

    void start_list (Node **first);
    Node *create_node (int code, char *art, char *alb);
    void insert_list (Node **first, Node *next);
    void print_list (Node *p);
    void exit_list (Node **p);

    int main(int argc, char *argv[])
    {
      Node *first;
      Node *new;
      int n;
      char artist[MAX];
      char album[MAX];
      start_list(&prim);
      do{
        printf("Please enter a number for the next Node or 0 to exit the list: ");
        scanf("%d",&n);
        if(n==0)break;
        printf("\nNow enter the artist's name: ");
        scanf("%s",&artist);
        printf("\nType the album tytle now: ");
        scanf("%s",&album);
        printf("\n\nCode: %d ",n);
        printf("\nArtist: %s ",artist);
        printf("\nAlbum: %s \n",album);
        new=create_node(n,artist,album);
        insert_list(&first,new);
      }while(n!=0);
      print_list (prim);
      exit_list(&prim);
      system("PAUSE");  
      return 0;
    }

    void start_list (No **prim){
      *prim=NULL;
    }  

    Node *create_node (int code, char *art, char *alb){
      Node *new;
      new=(Node*)malloc(sizeof(Node)); 
      new->code=code;
      new->artist=art;
      new->album=alb;
      new->next=NULL;
      return new;
    }

    void insert_list (Node **first, Node *new){
      new->next=*first;
      *first=new;
    }

    void print_list (Node *p){
      Node *aux=p;
      while (aux!=NULL){
        printf("\n\nCode: %d ",aux->code);
        printf("\nArtist: %s ",aux->artist);
        printf("\nAlbum: %s \n",aux->album);
        aux=aux->next;
      }
    }

    void exit_list (Node **p){
      Node *aux=*p;
      while(aux!=NULL){
        *p=(*p)->next;
        free(aux);
        aux=*p;
      }
    }
4

2 回答 2

1
  Node* first = NULL;
  new->artist = strdup(art);
  new->album = strdup(alb);

并在 exit_list 中释放它们,就在free(aux).

    free(aux->art);
    free(aux->alb);
    free(aux);
于 2013-05-03T16:52:21.923 回答
0

您的 create_node 函数将 char 指针艺术家和专辑设置为指向主函数中的艺术家和专辑数组。每次迭代只是重写存储在这些数组中的内容。因此,每个节点都指向相同的字符串,并且在进程结束时,最近输入的字符串位于数组中。

您需要为每个新字符串分配(例如使用 malloc 或使用堆的字符串函数)存储空间,以便字符串在调用之间保持不变并且不会被覆盖。

于 2013-05-03T17:12:41.113 回答