繁体   English   中英

我一直遇到分段错误,我不知道为什么

[英]I keep getting a segmentation fault and I don't know why

我正在用C编写一个链表程序,我试图将链表写入文件。 在程序询问用户他们想要保存文件的名称之后,我输入名称并按Enter键然后我得到分段错误并退出程序。 我迷失了,试图找出原因。 我唯一能想到的是do..while循环,但我在我的程序中使用其他代码,它工作正常。 提前致谢!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Inventory {
    int partID;
    int quantity;
    float price;
    struct Inventory *next;
};

void saveFile(struct Inventory**);

int main()
{
    struct Inventory *first = address location of first structure in list;

    saveFile(&first);

    return 0;
}

void saveFile (struct Inventory **firstPtr)
{
    struct Inventory *prev = NULL;
    char ext[5] = ".csv";
    char fileName[15];
    char c;

    FILE *fp;

    printf("   What would you like to save your linked list as, up to 14 characters: ");
    scanf("%s", fileName);
    strcat(fileName, ext);

    if((fp = fopen(fileName, "r")) != NULL) {
        printf("   File already exists. Would you like to overwrite? [Y/N] ");
        scanf("\n%c", &c);

        if(c == 'Y' || c == 'y') {
           fclose(fp);
           fp = fopen(fileName, "w+");
        } else {
           printf("   Would you like to add to the list? [Y/N] ");
           if(c == 'y' || c == 'Y') {
               fclose(fp);
               fp = fopen(fileName, "a");
           } else {
               fclose(fp);
               return;
           }
        }

    } else {
        fclose(fp);
        fp = fopen(fileName, "w+");
    }   

    do {
        prev = *firstPtr;
        fprintf(fp, "%d,%d,%f\n", prev->partID, prev->quantity, prev->price);
        prev = prev->next; 
    } while (prev->next != NULL); 

    fclose(fp);
}

您的循环不会防止第一个条目可能为NULL ,请尝试使用以下循环链接列表:

while (prev) {
    fprintf(fp, "%d,%d,%f\n", prev->partID, prev->quantity, prev->price);
    prev = prev->next;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM