Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structs not working, getting garbage output

Tags:

c

struct

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;
}
like image 403
Andy Avatar asked Apr 23 '26 20:04

Andy


1 Answers

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

like image 138
shree.pat18 Avatar answered Apr 26 '26 09:04

shree.pat18



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!