C programming Question

JC724

Weaksauce
Joined
Jan 20, 2016
Messages
118
So I am trying to practice creating linked list. I run into a bug immediately using scanf. I am using a printf statement followed by a scanf but it seems to be working backwards. Like the printf s will not run until after scanf. Which is really weird to me.

#include<stdio.h>



//linked list node
typedef struct myList {
int info; //data info
struct mylist *link; //self reference link
}Node;

int main()
{
printf("Starting\n");

Node *a = (Node*)malloc(sizeof(Node));
Node *b = (Node*)malloc(sizeof(Node));
Node *c = (Node*)malloc(sizeof(Node));

a ->link = NULL;
b ->link = NULL;
c ->link = NULL;

//this section is working backwards
printf("a data = ?");
scanf("%d", &a->info);




putchar('\n');

return 0;

}

terminal output:

1(input 1 here)
Starting
a data = ?


Starting and a data =?, should be printing 1st??
 
What compiler are you using?

As written your code works fine, here is my output:

ZeanwJr.png


You can try flushing the output before the scan I suppose
 
Last edited:
Standard output is buffered unless you tell it not to be. That means it won't print until there's a newline or the buffer is flushed. You can either set stdout not to buffer using setbuf(stdout, NULL); or call fflush(stdout); after your printf call.
 
Back
Top