简体   繁体   中英

Nested Array of Structs inside another Struct

I am trying to model a cache simulator, I didn't post all my code because I have all of the logic set up already, but I am trying to use structs to accomplish the task at hand.

I have two types of structs, one for Lines, which contain:

int LineIndex unsigned Long tagbits int vbit

I then have a struct set which contains:

int LRU int SetIndex Line* SetLines

Now I am picturing this like a two dimensional array. I make a variable Cache which is a pointer to a Set. The code is below.....

typedef struct{
    int Vbit;
    unsigned long LineTagBits;
    int LineIndex;
}Line;

typedef struct{
    Line* SetLines;
    int LRU;
    int SetIndex;
}Set;

int s, b, E, SetNum, BlockNum, i, c = 0;
unsigned long SetMask, BlockMask,TagMaks = 0;
Set* Cache = NULL;
Line* SetLines = NULL;


void MallocAndInitialize(){
    Set Cache[SetNum];
    for (int i = 0; i < SetNum; i++){
        Cache[i].LRU = 0;//set LRU line
        Cache[i].SetIndex = i;//set set INDEX
        printf("You are at Set %i \n", Cache[i].SetIndex);
        Cache[i].SetLines = (Line *)malloc(E * sizeof(Line));
        for (int j = 0; j < E; j++){
            Cache[i].SetLines[j].Vbit = 0;
            Cache[i].SetLines[j].LineIndex = j;
            Cache[i].SetLines[j].LineTagBits = 0;
            printf("Set %i, Line %i\n", Cache[i].SetIndex, Cache[i].SetLines[j].LineIndex);
            }
        }
}


int main(int argc, char *argv[]){


    while ((c = getopt(argc, argv, "s:E:b:")) != -1)
{
        switch (c){
        case's':
          s = atoi(optarg);
          SetNum = 1 << s;
          MallocAndInitialize();
          break;
        case'E':
          E = atoi (optarg);
          break;
        case 'b':
          b = atoi (optarg);
          BlockNum = 1 << b;
          break;
        default:
          printf("Error!");
          exit(1);
        }
    }

    //printSummary(0, 0, 0);
    free(Cache);
    return 0;
}

Now the Problem is it will do the first print statement in MallocandInitialize, but it will not do the second print statement. I am trying to figure out if I am not accessing each line correctly. Any help is much appreciated.

Thanks

Your program is dependent on the order of the command line arguments.

-E is needed to set the global variable 'E'. But -s will call MallocAndInitialize which reads E.

This is not a good organization of your code.

I'd suggest moving MallocAndInitialize out of the loop that processes the arguments.

I don't see any assurance that when MallocandInitialize is called, E is assigned a particular value.

Are you sure that E is greater than zero?

please try to print it before going into the inside loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM