0

我很确定这是一个简单的问题,但我正在尝试创建一个实现动态结构数组的数据结构。

每个结构都将实现一个链表。

所以我认为我想要一个指针数组,它将指向每个列表的头部。出于某种原因,分配方法变量会给我一个段错误。如果可以的话,我很想解释一下我做错了什么。谢谢!

哦,另外,所有这些都在一个名为 Cache 的类中,所以这就是为什么有些变量似乎没有定义,但我向你保证它们是。索引[i]->next = NULL 上的程序段错误;以及该行下方的类似行。

        typedef struct setNode {
    char valid, dirty;
    unsigned int tag;
    setNode *next;
    Cache *nextCache;

} set;
    set **indexes;

    arrayLength = cache_size / block_size;

    indexes = new setNode *[arrayLength];

    set *temp;

    //Step through the array. The array is full of pointers to "Dummy Nodes"
    for (size_t i = 0; i < arrayLength; i++) {
        indexes[i]->next = NULL;
        indexes[i]->valid = 0;
        indexes[i]->dirty = 0;
        indexes[i]->tag = 0;
        //create empty linked list for each tag spot (One for direct mapped. etc...)

         for(size_t i = 0; i < associativity; i++)
         {
         temp = indexes[i];
         temp->next = new setNode;
         temp = temp->next;
         temp->next = NULL;
         temp->valid = 0;
         temp->dirty = 0;
         temp->tag = 0;
         }

    }

}
4

1 回答 1

1

indexes是指向对象的指针数组set,但它们未初始化。它们不指向实际set对象,而只是指向随机内存位置。尝试写入随机存储器是分段违规的本质。

在使用指针之前,您需要分配set对象并使指针指向它们——即,

for (size_t i = 0; i < arrayLength; i++) {
    indexes[i] = new set;
    indexes[i]->next = NULL;
    indexes[i]->valid = 0;
    ...
于 2012-04-26T02:58:33.437 回答