将值赋给结构指针内的结构指针数组中的索引

时间:2016-03-20 21:07:48

标签: c arrays pointers struct

我目前在将NODE类型对象分配到NODE*结构内的INV_PAGE_TABLE数组时遇到问题。

结构如下:

typedef struct node {
    int pid;
    int p;
    int offset;
    unsigned TAG;
} NODE;

typedef struct invTablePage {
    NODE *pageTable;
    int frameSize;
    int currentSize;
    int totalSize;
    int oldest;
    int maxIndex;
} INV_PAGE_TABLE;

invTablePage按如下方式分配:

void initInverted(INV_PAGE_TABLE *invTable, int memSize, int frameSize) {
    //Malloc inverted page table
    invTable = malloc(sizeof(struct invTablePage));
    //Save frameSize
    invTable->frameSize = frameSize;
    //Save totalSize
    invTable->totalSize = memSize / frameSize - 1;
    //Save currentSize
    invTable->currentSize = 0;
    //Set oldest
    invTable->oldest = 0;
    //Malloc array inside of page table
    invTable->pageTable = malloc(sizeof(NODE) * invTable->totalSize);
}

最后调用分段错误的方法

void addToPageTable(struct invTablePage *invTable, NODE *node) {
    NODE tempNode;
    //If pageTable is not full
    int currentSize = invTable->currentSize;

    if (invTable->currentSize != invTable->totalSize) {
        //Add Entry at index of currentSize

        /*FOLLOWING LINE CRASHES PROGRAM*/
        invTable->pageTable[currentSize] = node;

        //Update currentSize
        invTable->currentSize++;
        //If pageTable is full
    } else {
        //Set temp to oldest
        tempNode = invTable->pageTable[invTable->oldest];
        //Set oldest to node
        invTable->pageTable[invTable->oldest] = *node;
    }
}

1 个答案:

答案 0 :(得分:0)

请注意,例如,在数组[10]中,索引从0到9

运行

所以你的总大小应该是invTable-> totalSize = memSize / frameSize; currentSize不应超过invTable-> totalSize - 1。 但我认为你必须分配memSize / frameSize而不是memSize / frameSize - 1 ...

我不确定我的答案是否正确,请尝试一些printf ......