Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

arrays - Having code issue in C

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

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

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...