所以我有一个输入文件,其中包含:
1 2 288815 1 13 60980
1 6 257684 1 8 250730
0 2 468583 0 0 61388
1 6 210352 0 3 23664
0 0 358489 1 13 219326
0 0 9676 0 3 402661
0 3 280447 0 3 288153
1 7 4957 0 0 397725
此信息已逐行读入数组。
每行的第一个和第四个数字是有效支票,第二个和第五个数字是标签,第三个和第六个数字是地址。
我需要创建一个带有三个参数的函数:myArray,index,tag
该函数将检查参数中给出的索引处的行。它将首先检查行中是否有与参数中的标记相等的标记。如果是,那么它将检查有效数字是1还是0.如果它是1,那么它应该返回标记之后的地址。否则,它应该返回“页面错误”。
这是我第一次尝试:
char *lookUpTLB(char **array, int TLBI, int TLBT)
{
if (array[TLBI][2] == TLBT)// checks if the second number in the array is equal to the tag
{
//char **ar = array[TLBI] + 2;
if (array[TLBI][0] == '1')//checks the valid number
{
return array[TLBI]+11;
}
else
{
return "Page Fault";
}
}
else if (array[TLBI][13] == TLBT)//checks if the 13th index is equal to the tag
{
if (array[TLBI][11] == '1')//checks the valid number
{
return array[TLBI] + 15;
}
else
{
return "Page Fault";
}
}
else
{
return "Page Fault";
}
}
此代码存在一些问题,但主要思想是存在的。我不能像使用我的代码那样使用索引,因为并非所有数字都是相同的长度。我被告知我可以使用按位运算符来做到这一点,但我对如何做到这一点非常困惑。
以下是我想要发生的例子:
调用lookUpTLB(myArray,0,2);应该返回288815
调用lookUpTLB(myArray,0,13);应该返回60980
调用lookUpTLB(myArray,3,3);应该返回页面错误,因为有效数字是0
调用lookUpTLB(myArray,3,6);应该返回210352
我对C很新,有关我应该如何做这个功能的任何帮助?如果我需要更清楚,请告诉我。
答案 0 :(得分:0)
,如果不是固定的长度,似乎应该将他转换为数字格式化文件。
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
typedef struct data {
char valid;
int tag;
int32_t address;
} Data;
typedef struct rec {
Data data[2];
} Record;
int32_t lookUpTLB(Record *array, int index, int tag);
int main(void){
Record array[16];
int n=0;//number of record
FILE *fp = fopen("data.txt", "r");
while(6==fscanf(fp, " %c %d %" SCNd32 " %c %d %" SCNd32 ,
&array[n].data[0].valid, &array[n].data[0].tag, &array[n].data[0].address,
&array[n].data[1].valid, &array[n].data[1].tag, &array[n].data[1].address))
{
++n;
}
fclose(fp);
int index, tag;
int32_t address;
while(1){
printf("index(-1.:end) and tag\n");
if(2!=scanf("%d %d", &index, &tag) || index == -1)
break;
if(0>(address = lookUpTLB(array, index, tag)))
printf("Page fault\n");
else
printf("%" PRId32 "\n", address);
}
return 0;
}
#define PAGE_FAULT -1
int32_t lookUpTLB(Record *array, int TLBI, int TLBT){
if(array[TLBI].data[0].tag == TLBT){
return array[TLBI].data[0].valid == '1' ?
array[TLBI].data[0].address :
PAGE_FAULT;
} else if(array[TLBI].data[1].tag == TLBT){
return array[TLBI].data[1].valid == '1' ?
array[TLBI].data[1].address :
PAGE_FAULT;
}
return PAGE_FAULT;
}
<强>样本强>:
index(-1.:end) and tag
0 2
288815
index(-1.:end) and tag
0 13
60980
index(-1.:end) and tag
3 3
Page fault
index(-1.:end) and tag
3 6
210352
index(-1.:end) and tag
-1.