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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With