2012-04-26 154 views
0

我很确定这是一个简单的问题,但我想创建一个数据结构,实现动态数组结构。动态指针结构抛出指针SIGSEGV成员变量赋值

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

所以我认为我想要一个指针数组,它将指向每个列表的头部。出于某种原因,分配方法变量给了我一个seg故障。如果可以的话,我会很乐意解释我做错了什么。谢谢!所有这些都在一个名为Cache的类中,所以这就是为什么有一些变量看起来没有被定义,但我向你保证它们是。程序seg错误索引[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; 
     } 

    } 

} 

回答

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; 
    ... 
+0

权,这是有道理的......我加索引[i] =新集;在for循环的顶部,现在它工作。谢谢!愚蠢的我,我没有意识到你需要初始化结构和类,但由于数组只有指针,这是有道理的。 – usssrrrrrr1 2012-04-26 03:05:26