我在initializeStruct函數中遇到了分段錯誤。 我想要一個2D數組指針。每個2D數組索引都包含三種類型的結構。對二維數組指針使用malloc會導致分段錯誤
這裏的結構:
struct cacheLine {
int validBit;
int tag;
int LRUcounter;
};
這是一個失敗的方法:
void initializeStruct(struct cacheLine **anyCache){
int i, j;
for (i=0;i<S;i++){
for(j=0;j<E;j++){
anyCache[i][j].validBit = 0; //I am getting a Segmentation fault
anyCache[i][j].tag = 0;
anyCache[i][j].LRUcounter = 0;
}
}
return;
}
在主,我使用malloc創建我的二維數組指針:
int main(int argc, char** argv){
int opt;
char *t;
//looping over arguments from command line
while(-1 != (opt = getopt(argc, argv, "s:E:b:t:"))){
//determine which argument it's processing
switch(opt){
case 's':
s = atoi(optarg);
break;
case 'E':
E = atoi(optarg);
break;
case 'b':
b = atoi(optarg);
break;
case 't':
t = optarg;
break;
//too many arguments
default:
printf("wrong argument\n");
break;
}
}
//create array
S = 1 << s;
B = 1 << b;
//allocate memory
struct cacheLine **cacheArray = malloc(sizeof(struct cacheLine)*S*E);
//Initialize Structs
initializeStruct(cacheArray);
可能的重複[如何正確設置,訪問和釋放C中的多維數組?](http://stackoverflow.com/questions/12462615/how-do-i-correctly-set-up- access-and-free-a-multidimensional-array-in-c) – Lundin