cSorted sequentially with language dynamic memory allocation

Asked 2 years ago, Updated 2 years ago, 40 views

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

struct student {
        int id;
        char name[20];
    int score[4];
        struct student *next;
};

int main()
{

        int count = 0, id,sc[4];
        char name[20],line[200];
        struct student *p, *head, *node = NULL;
        printf("Please enter your school name and name"\n");
        fgets(line, 200, stdin);
        while (fgets(line, 200, stdin) != NULL) {
            sscanf(line, "%d %s %d %d %d %d", &id, name,
               &sc[0],&sc[1],&sc[2],&sc[3]);
                p = (struct student *) malloc(sizeof(struct student));
                node = (struct student *) malloc(sizeof(struct student));
                if (head == NULL)
                        head = p;
                else
                        node->next = p;
                node = p;
                if (p == NULL) {
                        perror("malloc");
                        exit(1);
                }
                p->id = id;
                strcpy(p->name, name);
                node=p->next;
        for(int i=0; i< 4; i++)
           p->score[i]=sc[i];
        }

        printf("\n* Student Information *\n");
        p = head;
        while (p != NULL) {
                count++;
                printf("Grade: %d Name: %s: ", p->id, p->name);
        for(int i=0; i< 4; i++)
           printf("%6d", p->score[i]);
        printf("\n");
                p = p->next;
        }

        printf ("Total %d people".\n", count);
        exit(0);
}

// Fix the parts in order? How do I arrange it?자체가ㅠ 순차 The files themselves are sorted sequentially, so I think we can print them out while connecting them to nodes, but I keep asking because it doesn't work... It is done by Moba Xsterm, and it is executed by putting the txt file in redirection. If you do this, you'll get a segmentation error or 39 lines, but you'll only get one line, so I'm asking you a questionㅜ<

c

2022-09-22 08:08

1 Answers

// I can't see the part.

p=(structure student *) malloc(sizeof(structure student)));
node = (struct student *) malloc(sizeof(struct student));
if (head == NULL)
      head = p;
else
node->next = p;
node = p;
f (p == NULL) {
        perror("malloc");
        exit(1);
}
 p->id = id;
strcpy(p->name, name);
 node=p->next;

I think there's a problem with this part, too. I think you're trying to use node as a pointer to the node that you're pointing to, and then you don't have to do a dynamic assignment. The node pointer just moves every time it is added to the list and points to the current node.


2022-09-22 08:08

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.