如何修复“访问冲突写入位置0xFFFFFFCD。”?

时间:2019-06-17 14:26:20

标签: c file linked-list scanf

我想从FILE读取数据并将其保存到链接列表,而我的问题显然是由读取命令“ fscanf”引起的。

我正在尝试创建一个函数,该函数接收链表的头和指向文件的指针。该函数从文件中读取数据并将其保存到节点中,然后将该节点连接到链表的开头,即连接到头,而不是末尾。

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

#define NameLength 15

typedef struct Product {
    char ProductName[NameLength];
    int Quantity;
    int Price;
    char Premium;
}Product;

typedef struct ProductList {
    Product P;
    struct ProductList* next;
}ProductList;

void DeleteList(ProductList*);
void ErrorMsg(const char*);
int CheckInList(ProductList*, const char*);

void CreateProducts(ProductList *head, FILE *fp) {
    ProductList *temp = (ProductList*)malloc(sizeof(ProductList));
    //If the dynamic memory allocation for temp has failed, print a 
message and exit the program.
    if (!temp) {
        DeleteList(head);
        ErrorMsg("Error: Memory allocation of temp in CreateProducts has 
failed.");
     }

    temp->next = NULL;
    while (!feof(fp)) {
        fscanf(fp, "%s%d%d%c", temp->P.ProductName, &temp->P.Quantity, 
&temp->P.Price, temp->P.Premium);
        if (CheckInList(head, temp->P.ProductName))
            printf("Error: Product is already found in the list.\n");
        else {
            if (temp->P.Quantity < 0)
            printf("Error: Quantity of the product cannot be 
negative.\n");
            else {
                if (temp->P.Price < 0)
                    printf("Error: Price of the product cannot be 
negative.\n");
                else
                {
                    //Adding the product to the beginning of the list 
every time.
                    if (head == NULL)
                        head = temp;
                    else
                    {
                        temp->next = head->next;
                        head->next = temp;
                    }
                }
            }
        }
    }
    if (head != NULL)
        printf("Products' information have been received.\n");
    else
        ErrorMsg("Products' information have NOT been received.");
}

1 个答案:

答案 0 :(得分:5)

打开编译器的警告! It will literally give you the answer.

main.cpp: In function 'void CreateProducts(ProductList*, FILE*)':
main.cpp:33:20: warning: format '%c' expects argument of type 'char*', but argument 6 has type 'int' [-Wformat=]
         fscanf(fp, "%s%d%d%c", temp->P.ProductName, &temp->P.Quantity,
                    ^~~~~~~~~~
 &temp->P.Price, temp->P.Premium);
                 ~~~~~~~~~~~~~~~

(我知道它说main.cpp;这只是在线编译器的伪像,我将其置于C模式。)