Assigning a value to an integer in a C-linked list

I have a question about linked lists. For example, I have the following structures and functions.

struct node {
    int value;
    struct node *next;
};

struct entrynode {
    struct node *first;
    struct node *last;
    int length;
};
void addnode(struct entrynode *entry) {
    struct node *nextnode = (struct node *)malloc(sizeof(struct node));
    int temp;
    if(entry->first == NULL) {
        printf("Please enter an integer.\n");
        scanf("%d", &temp);
        nextnode->value = temp;
        nextnode->next = NULL;
        entry->first = nextnode;
        entry->last = nextnode;
        entry->length++;
    } else {
        entry->last->next = nextnode;
        printf("Please enter an integer.\n");
        scanf("%d", nextnode->value);
        nextnode->next = NULL;
        entry->last = nextnode;
        entry->length++;
    }

}

In the first part of the if statement, I store the input in a temp variable and then assign it to a field in the structure. Otherwise, I tried to assign it directly, which did not work. How can I assign it directly?

Thank you for your time.

+3
source share
5 answers

Try scanf("%d", &(nextnode->value));

+5
source
    scanf("%d", nextnode->value);

You need to pass a pointer to the value element to keep scanf () happy. Fix:

    scanf("%d", &nextnode->value);

Perhaps one lesson to learn from this is to never mix data entry code with data structure change code.

Btw: , . , .

+2

-, .

:

scanf("%d", &(nextnode->value));

, !

  • , entrynode. , ?

  • :

    bool addnode ( entry entry entry), int);

  • , .

  • . .

  • printf scanf.

, , printf scanf , , elses.

+1

: scanf("%d", &(nextnode->value));

Generally speaking, as a comment on your code, avoid repeating code known as antipattern copy-paste. Reuse its maximum. Usually, if you find yourself in a situation to repeat the code, create a small function.

0
source

Also, check the reverse value of the calls malloc(). Also, do not leave the return value malloc()in the C programming language.

0
source

Source: https://habr.com/ru/post/1750197/


All Articles