3

Intuitively below should seemingly work, 1) define a structure; 2) attempt to load values; 3) print them.

This code creates an extra line break after the first but does not print out any of the values that user inputs.

#define NODES 5

typedef struct node
{
    int val;
    struct node* next;
}
node;

int main(void)
{
    node nodes[NODES];

    for (int i = 0; i < NODES; i++)
    {
        printf("Value of node %i: ", i);
        nodes[i].val = scanf("%i\n", &nodes[i].val); 
    }

    for (int i = 0; i < NODES; i++)
    {
        printf("Value of node %i: is %i \n", i, nodes[i].val);
    }

    return 0;
}
0

1 Answer 1

6

Change this line:

nodes[i].val = scanf("%i\n", &nodes[i].val); 

to this:

scanf("%i\n", &nodes[i].val); 

As per the man page, scanf returns the number of input items successfully matched and assigned. So your code is reading in the right value, but assigning the return value of scanf to the member, thereby overwriting the value assigned earlier.

Reference: http://man7.org/linux/man-pages/man3/scanf.3.html

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.