2

我正在尝试将项目添加到链接列表。代码编译正常,但是当我执行程序时,它在添加第一个节点之前崩溃。代码对我来说看起来不错,但我一定遗漏了一些东西。

该代码使用此问题所必需的全局链表。我认为我对它的使用可能是导致崩溃的原因。

主程序

#include <stdio.h>
#include <stdlib.h>
#include "LinkedList.h"

int main (int argc, char* argv[])

{
    LinkedList *canQueue;
    int ii;
    createList();

    FILE* f;
    f = fopen(argv[1], "r");

    if(f==NULL) 
        {
        printf("Error: could not open file");
        return 0;
        }


    for(ii = 0; ii < 10; ii++)
        {
        TinCan* tempCan = malloc(sizeof(TinCan));
        fscanf(f, " label_%d", &tempCan->label); /*Read info from file into label field*/
        insertLast(canQueue, tempCan); /*Inserts the new can into linked list*/
        }

    return 0;
}

链表.h

typedef struct TinCan
    {
    int label;
    } TinCan;

typedef struct Node
    {
    TinCan* data;
    struct Node *next;
    } Node;

typedef struct LinkedList
    {
    Node *head;
    } LinkedList;


void insertLast(LinkedList* list, TinCan *newData);
void createList();

extern LinkedList* canQueue;

链表.c

#include <stdio.h>
#include <stdlib.h>
#include "LinkedList.h"

LinkedList *canQueue;

void createList() /*creates empty linked list*/
  {
    canQueue = malloc(sizeof(LinkedList));
    canQueue->head = NULL;
  }

void insertLast(LinkedList* list, TinCan *newData)
    {
    Node* newNode = malloc(sizeof(Node));
    newNode->data = newData;
    newNode->next = NULL;

    if(list->head==NULL)
        {
        list->head=newNode;
        }

        else
            {
            Node* temp;
            temp = list->head;
            while(temp->next!=NULL)
                {
                temp = temp->next;
                }
             temp->next = newNode;
            }
  printf("Added to end");
  }
4

1 回答 1

1

根据您的回复,您需要从 main 中删除此声明:

LinkedList *canQueue;

它正在遮蔽全局canQueue,这意味着稍后当您调用时insertLast

insertLast(canQueue, tempCan);

您正在对未初始化的指针进行操作。

于 2013-05-15T02:09:38.253 回答