多项式通过C中的文件赋值

问题描述 投票:-3回答:1

我想将从文件输入的指数和系数信息分配给循环链表。

文件“a.txt”如下

8 3
7 2
3 0

但是,输出中也存在奇怪的值。我想让列表循环,但事实并非如此。

coef    expon 
3       0
7       2
8       3
7887744 0
7900240 0
7864656 0
7869712 0
7900240 0
7864656 0
7869712 0

拜托,我找不到解决方案。

#include <stdio.h>
#include <stdlib.h>
typedef struct polyNode* polyPointer;
typedef struct polyNode{
    int  coef;
    int expon;
    polyPointer link;
};

int main()  {
    polyPointer A, B, C = (polyPointer)malloc(sizeof(polyPointer)) ;
    FILE *fa, *fb ;
    int a;

    fa = fopen("a.txt", "r");
    if(fa==NULL){
        printf("file open error\n");
        return 1;
    }
    if(fb==NULL){
        printf("file open error\n");
        return 1;    
    }
    A = create_circle_linked_poly(fa);
    printf("coef        expon\n");
    int i;
    for(A; i<10; A=A->link, i++)
        printf("%d  %d\n", A->coef, A->expon); 
    return 0;
}

polyPointer create_circle_linked_poly(FILE *a){
    polyPointer head = malloc(sizeof(polyPointer));
    polyPointer temp = malloc(sizeof(polyPointer));
    first = head;
    int res;
    while(1){
        polyPointer p =(polyPointer) malloc(sizeof(polyPointer));
        res = fscanf(a, "%d %d", &p->coef, &p->expon);
        if(res==EOF)break;
        p->link = head;
        head = p;    
    }
    return head;   
}
c file-io polynomials
1个回答
0
投票

正如其名称所示,你的polyPointer是一个指针。所以如果你malloc(sizeof(polyPointer))你只分配指针的大小。但是你想要分配一个对象,那样做 malloc(sizeof(*polyPointer))

你进一步检查是否用fb打开了if(fb==NULL){...。幸运的是fb是未初始化的,probaly不会是NULL,但你从来没有为文件调用fopen

我在你的for循环中看到你迭代直到i是10但a)i未初始化,因此可能是-123456左右,并且b)你永远不会检查你是否已经到达链接列表的末尾。所以打印的最后一个元素是未定义的(垃圾)。所以将for循环更改为: for(i=0; i<10 && A!=NULL; A=A->link, i++)

并且不要施放malloc的结果。它返回一个void指针,它与任何指针类型兼容。

© www.soinside.com 2019 - 2024. All rights reserved.