Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Can anyone please tell me what is the problem with this code?

There is no issue in the compilation of this code but after compilation when I enter the data of Array of Objects of structure, the data is not entered after one loop.

#include<stdio.h>
struct process{
    char name;
    int arv;
    int burst;
}p[10];
int sort(struct process p[],int n){
    int i,j;
struct process t;
    for(i=0;i<n;i++){
        for(j=0;j<n-1-i;j++){
            if(p[j].arv>p[j+1].arv){
                p[j]=t;
                p[j]=p[j+1];
                p[j+1]=t;
            }
        }
    }
return 0;
}
int main(){
    int i,n;
    printf("Enter Number Of Processes");
    scanf("%d",&n);
    for(i=0;i<n;i++){
        scanf("%c",&p[i].name);
        scanf("%d",&p[i].arv);
        scanf("%d",&p[i].burst);
    }
    sort(p,n);
    for(i=0;i<n;i++){
        printf("%c",p[i].name);
        printf("%d",p[i].arv);
        printf("%d",p[i].burst);
    }
return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
213 views
Welcome To Ask or Share your Answers For Others

1 Answer

Read documentation of scanf(3) and of fflush(3)

Always test the result of scanf

printf("Enter Number Of Processes");
fflush(NULL);
if (scanf("%d",&n)<1) 
 { perror("scanf nb process"); exit(EXIT_FAILURE); ; }

(do likewise for your other calls to scanf ...)

and at least call fflush at end of each for loop, e.g.

for(i=0;i<n;i++){
    printf("%c",p[i].name);
    printf("%d",p[i].arv);
    printf("%d",p[i].burst);
    fflush(NULL);
}

since stdio(3) is buffered. BTW, you'll be surprised by the output. You generally should end each (or at least most) printf format string with

BTW, you should compile with all warnings & debug info (gcc -Wall -Wextra -g) and you should use the debugger (gdb)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...