程序提供正确的输出,然后挂起。 [英] Program gives correct output and then hangs.

查看:76
本文介绍了程序提供正确的输出,然后挂起。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#包括< iostream.h> 
using namespace std;
#include< conio.h>
int main()
{
int pgn,fn;
int i,j = 0,k,count = 0,avail;
int frame [10];
cout<<输入页面数量\ n;
cin>> pgn;
int * a =(int *)malloc(sizeof(int));
cout<<输入访问页面的顺序\ n;
for(i = 0; i< pgn; i ++)
cin>> a [i];
cout<<输入帧数\ n;
cin>> fn;
for(i = 0; i< fn; i ++)
frame [i] = - 1;
cout<<PAGE NO。<<\t<<FRAME STATUS \ n;
for(i = 0; i< pgn; i ++)
{
cout<< a [i]<<\t;
avail = 0;
for(k = 0; k< fn; k ++)
{
if(frame [k] == a [i])
{
avail = 1 ;
休息;
}
}
if(!avail)
{
frame [j] = a [i];
j =(j + 1)%fn;
count ++;
for(k = 0; k cout<< frame [k]<<\t;
}
cout<< endl;
}
cout<<页面错误的数量是<< count;
免费(a);
getch();
}

解决方案

想想这个



< pre lang =c ++> int * a =( int *)malloc( sizeof int ));





正在做你想要的 - 你所做的就是分配一块等于int大小的内存,并将它存储在一个列表中..而我认为你想要的是malloc一个动态的整数数组/ ints - 略有不同



也许你需要类似



 a = malloc(pgn *  sizeof  int )); 





你还假设你得到的内存都是零 - 不好,你应该把你的数组设置为零。



'g'


#include<iostream.h>
using namespace std;
#include<conio.h>
int main()
{
    int pgn,fn;
    int i,j=0,k,count=0,avail;
    int frame[10];
    cout<<"Enter the no. of pages\n";
    cin>>pgn;
    int *a=(int *)malloc(sizeof(int));
    cout<<"Enter the order in which pages are accessed\n";
    for(i=0;i<pgn;i++)
    cin>>a[i];
    cout<<"Enter the no. of frames\n";
    cin>>fn;
    for(i=0;i<fn;i++)
    frame[i]=-1;
    cout<<"PAGE NO."<<"\t"<<"FRAME STATUS\n";
    for(i=0;i<pgn;i++)
    {
        cout<<a[i]<<"\t";
        avail=0;
        for(k=0;k<fn;k++)
        {
            if(frame[k]==a[i])
            {
                avail=1;
                break;
            }
        }
        if(!avail)
        {
            frame[j]=a[i];
            j=(j+1)%fn;
            count++;
            for(k=0;k<fn;k++)
            cout<<frame[k]<<"\t";
        }
        cout<<endl;
    }
    cout<<"The no. of page faults is "<<count;
    free(a);
    getch();
}

解决方案

think about wether this

int *a=(int *)malloc(sizeof(int));



is doing what you want - what you've done is allocate a piece of memory equal to the size of an int, and store it in a list.. whereas what I think you want, is to malloc a dynamic array of integers/ints - slightly different

maybe you need something like

a = malloc(pgn * sizeof(int));



you also make an assumption that the memory you're getting it all zero's - bad, you should memset your array to zero.

'g'


这篇关于程序提供正确的输出,然后挂起。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆