-3

I want to assign the exponent and coefficient information input from the file to the circular linked list.

file "a.txt" is as follows

8 3
7 2
3 0

However, there are also strange values ​​in the output like this. I wanted to make the list circular, but it doesn't.

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

please, I can't find the solution.

#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œur
  • 37,241
  • 25
  • 195
  • 267
박진근
  • 1,003
  • 2
  • 6
  • 6
  • 1
    `sizeof(polyPointer)` looks wrong, seeing `polyPointer` is a typedef'd pointer – pmg Dec 08 '18 at 13:35
  • 1
    Hint: don't cast the return value of `malloc`; hint2: use the object itself as operand of `sizeof`; hint3: don't hide the pointerness of identifiers behind a `typedef`. `struct polyNode *head = malloc(n * sizeof *head);` – pmg Dec 08 '18 at 13:38
  • i'm totally done – 박진근 Dec 08 '18 at 13:54

1 Answers1

0

Your polyPointer is, as its name says, a pointer. So if you malloc(sizeof(polyPointer)) you are allocating only the size of a pointer. But you want to allocate an object, so do
malloc(sizeof(*polyPointer)).

You further check if fb was opened with if(fb==NULL){.... Luckily fb was uinitialized and probaly will not be NULL, but you never called fopen for the file.

And I see in your for loop that you iterate until i is 10 but a) i is uninitialized and so could be -123456 or so, and b) you never check if you have reached the end of the link list. So the last elements printed are undefined (garbage). So change the for loop to:
for(i=0; i<10 && A!=NULL; A=A->link, i++).

And don't cast the result of malloc. It returns a void pointer, which is compatible with any pointer type.

Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41