[英]Not sure why I'm getting this output for first element in char array
我收到第一個進程ID名稱的奇怪輸出,不知道為什么。 也許我告訴它打印char數組的方式?
下面的代碼:
int main(){
int a; //variable used for: total number of processes
int i,j,k,l; //used for loops
int t1; //temporary variables
int burst[10],ttime[10],wait[10];
char process_name[10][11]; // array for storing up to 10 strings, with each up to length of 10 characters
char process_name_temp[10][11]; //temp variable for process name
float wait_time,wait_time_avg;
/*Pre-Fill burst and wait arrays with times of 0*/
for(i=0;i<10;i++){
burst[i]=0;
wait[i]=0;
}
wait_time_avg = 0; //set the wait time average to zero
printf("Please Enter Total Number of Processes Desired\n"); //
scanf("%d",&a); //get input from user:total number of processes
/*get user input from user: burst time for each process, process name for each process*/
for(i=0;i<a;i++){
printf("Please Enter Process Name(one word)\n");
scanf("%s", &process_name[i][11]);
printf("Please Enter Burst Time\n");
scanf("%d", &burst[i]);
}
for(i=0;i<a;i++){
for(j=1;j<a;j++){
if(burst[i]>burst[j]){
t1 = burst[i];
process_name_temp[i][11] = process_name[i][11];
burst[i] = burst[j];
process_name[i][11] = process_name[j][11];
burst[j] = t1;
process_name[j][11] = process_name_temp[j][11];
}
}
wait[0] = 0;
for(i=0;i<a;i++)
wait[i+1] = wait[i] + burst[i];
for(i=0;i<a;i++){
//ttime[i] = wait[i] + burst[i];
wait_time_avg = 0;
wait_time = 0;
wait_time_avg = wait_time_avg + wait[i];
}
wait_time_avg = wait_time_avg/a;
printf("\n\t Process ID \t Waiting Time \t Burst Time \n");
for(i=0;i<a;i++)
printf("\t %s \t\t %d \t\t\t %d \n\n", process_name[i],wait[i],burst[i]);
printf("Waiting Time Average: %f \n", wait_time_avg);
}
返回0;
}
如果有人可以幫助我,那就太好了。 這可能是一個簡單的解決方法-我錯過或忽略的一些地方。 謝謝!
在您的scanf("%s", &process_name[i][11]);
。 這會將指針傳遞到process_name
數組末尾的一個元素。 所以你的scanf()
調用是錯誤的,應該是
scanf("%10s", process_name[i]);
由於process_name
數組未正確初始化,因此程序表現出不確定的行為。
您必須檢查從scanf()
的返回值,該返回值專門用於"%d"
說明符。 如果您不這樣做,則由於讀取未初始化的數據,您還希望程序調用未定義的行為。
在開始for
循環之前,應檢查a < 10
。 因此,在詢問用戶項目數量之后,請確保用戶確實輸入了合理/有效的內容。
在代碼的嵌套for循環中,您訪問每個數組中最后一個元素之后的一個元素。 索引從0
到N - 1
,因此訪問x[N]
不會按預期進行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.