0

我已经为最佳页面替换算法编写了代码。我正在接受对页面数组的引用字符串。但是页面的值在结束事件时正在改变,尽管我没有修改页面数组。我不知道它为什么会改变。请提供一些帮助。我首先在页面中显示了值,最后两者都不同。

#include <stdlib.h>

struct frame
{
    int value;
    int count;
};

int getlfu(struct frame *f, int n)
{
    int max = 0;
    for (int i = 0; i < n; i++)
    {
        if (f[i].value == -1)
            return i;
        if (f[max].count < f[i].count)
        {
            max = i;
        }
    }
    return max;
}

int main()
{
    int i, j, nop, n, hit = 0, fault = 0, pos = 0, flag = 0, choice, x = 1000;
    printf("Enter the no of frames in main memory:");
    scanf("%d", &n);
    printf("Enter the no of values in reference string");
    scanf("%d", &nop);
    int page[nop];
    struct frame f[n];
    printf("Enter the refernce string:");
    for (i = 0; i < nop; i++)
    {
        scanf("%d", &page[i]);
        if (i < n)
        {
            f[i].value = -1;
            f[i].count = 0;
        }
    }
       for (i = 0; i < n; i++)
    {
        f[i].value = -1;
        f[i].count = 0;
    }
    for(i=0;i<nop;i++)
        printf("%d ",page[i]);
    fault=hit=0;
    for (i = 0; i < nop; i++)
    {
        for (j = 0; j < n; j++)
        {
            printf("page[%d] is %d and f[%d].value is %d\n",i,page[i],j,f[j].value);
            if (page[i] == f[j].value)
            {

                flag = 1;
                hit++;
                f[j].count=0;
                for (int k = i + 1; k < nop; k++)
                {
                    if (f[j].value == page[k])
                        break;
                    else
                        f[j].count++;
                }
                for (int k = 0; k < nop && f[k].value != -1; k++)
                {
                    if (k != j)
                        f[k].count--;
                }
                break;
            }
        }
        if (flag == 0)
        {
            pos = getlfu(f, n);
            f[pos].value = page[i];
            fault++;
            f[pos].count = 0;
            for (int k = i + 1; k < nop; k++)
            {
                if (f[pos].value == page[k])
                    break;
                else
                    f[pos].count++;
                if (k == nop - 1)
                    f[pos].count = --x;
            }
            for (j = 0; j < n && f[j].value != -1; j++)
            {
                if (j != pos)
                    f[j].count--;
            }

        }
        printf("\n");
        flag = 0;
        for (j = 0; j < n; j++)
        {
            if (f[j].value != -1)
                printf("%d ", f[j].value);
            else
                printf("- ");
        }
        printf("\n");
      
    }
    printf("fault:%d        hit:%d    hit ratio:%d/%d\n", fault, hit, hit, hit + fault);
    for(i=0;i<nop;i++)
        printf("%d ",page[i]);
}
4

0 回答 0