gpt4 book ai didi

c - 结构体的全局数组,在程序中声明大小并全局使用而无需传递?

转载 作者:行者123 更新时间:2023-11-30 19:03:45 27 4
gpt4 key购买 nike

仅供引用,我正在制作一个缓存模拟器作为 C 项目。我需要声明一个结构体的全局 double 组,在程序中设置这个全局结构体数组的大小,然后在稍后的项目中使用该全局数组。

这是我所拥有的内容的简化版本:

// Declare globals
int mapping = 0;
int offset = 0;
int index = 0;

char* allocation;
char* writePolicy;

struct cache {
int validBit;
int dirtyBit;
unsigned int tag;
unsigned int nextToReplace;
};

void analyzeParameters(char* line, int lineNum) {

switch(lineNum) {
case 1:
mapping = atoi(line);
case 2:
offset = atoi(line);
case 3:
index = atoi(line);
case 4:
allocation = malloc(4);
strcpy(allocation, line);
case 5:
writePolicy = malloc(4);
strcpy(writePolicy, line);
}

}

setupCache() {
int numSets = 1 << index;

struct cache cache[mapping][numSets];

printf("Declared cache struct with size %d ", numSets);
printf("num of ways %d\n", mapping);

// initialize bits in cache to 0

int j;
int i;

for (j = 0; j < mapping; j++) {
for (i = 0; i < numSets; i++) {
cache[j][i].validBit = 0;
cache[j][i].dirtyBit = 0;
}
}

}

void hitChecker() {

for (d = 0; d < mapping; d++) {
if (cache[d][index].validBit == 1) {
if (cache[d][index].tag == tag) {
//found a hit

if (type == "r") {
// hit with a read instruction.
rhits++;


}
else if (type == "w") {
// hit with a write instruction
whits++;

}
}

else {
// tag in cache index is not equal to tag being checked

if (type == "r") {
// missed with a read instruction.
rmisses++;

}
else if (type == "w") {
// missed with a write instruction
wmisses++;

}
}
}
else {
//cache is not valid
printf("Cache has not been validated");
}
}

void main(int argc, char**argv) {

analyzeParameters(passInEachLineOfFile, this works not important);

setupCache();

hitChecker();

}

这一直有效,直到我尝试利用缓存结构。我全局声明它,在 setUpCache 中设置大小,然后在另一个方法中我想使用全局声明的 double 组。有没有一种方法可以在全局范围内使用它,或者我是否必须通过方法参数传递结构?

最佳答案

要获得具有运行时确定大小的全局缓存结构,请使用:

int mapping, numsets;
struct cache **cache;

和:

void init(int nmaps, int nsets)
{
cache=malloc(nmaps*sizeof(struct cache *));
for (int i=0;i<nmaps;i++)
cache[i]=malloc(nsets*sizeof(struct cache));
mapping= nmaps;
numsets= nsets;
}

关于c - 结构体的全局数组,在程序中声明大小并全局使用而无需传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53486289/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com