所以我有一个输入文件,其中包含:
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 还很陌生,请问我应该如何执行此功能有任何帮助吗?如果我需要更清楚,请告诉我。
最佳答案
,看来如果不是固定长度的话他应该转为数字简单格式化一下文件就可以了。
#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.
关于C 字符串和按位运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23510850/