【问题标题】:Not sure why I'm getting this output for first element in char array不知道为什么我会为 char 数组中的第一个元素获取此输出
【发布时间】:2016-10-24 18:07:54
【问题描述】:

我得到第一个进程 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;

}

如果有人可以帮助我,那就太好了。这可能是一个简单的修复——我错过或忽略了一些东西。谢谢!

【问题讨论】:

  • 请勿发布文字图片!

标签: c string algorithm


【解决方案1】:
  1. 在您的scanf("%s", &amp;process_name[i][11]); 中。这会在process_name 数组的末尾传递一个指向一个元素的指针。所以你的scanf() 调用是错误的,应该是

    scanf("%10s", process_name[i]);
    

    因此,由于 process_name 数组的初始化不正确,程序表现出未定义的行为。

  2. 您必须检查来自scanf() 的返回值,特别是"%d" 说明符。如果不这样做,您的程序也会因为读取未初始化的数据而调用未定义的行为。

  3. 您应该在开始 for 循环之前检查 a &lt; 10。因此,在询问用户项目数量后,请确保用户确实输入了合理/有效的内容。

  4. 在代码中的嵌套 for 循环中,您可以访问每个数组中最后一个元素之后的一个元素。索引从0 变为N - 1,因此访问x[N] 不会按预期工作。

【讨论】:

  • 告诉它寻找 10 个字符??你能具体解释一下为什么吗?顺便感谢您的快速响应!
  • @lsch91 我不明白你的新问题。
  • “%10s”部分,%和s之间的数字10到底是做什么的?
  • 防止scanf()从用户那里读取超过10个字符。
  • 好吧,有道理。谢谢。您在上面提到“process_name”数组初始化不正确。我在哪里做的? PS。请随意撕开我的代码 - 我是来学习的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-07
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
  • 2013-03-20
  • 1970-01-01
相关资源
最近更新 更多