gpt4 book ai didi

c - 使用 malloc 作为 2D 数组指针会导致段错误

转载 作者:行者123 更新时间:2023-12-02 21:47:13 25 4
gpt4 key购买 nike

我在initializeStruct 函数中遇到段错误。我想要一个二维数组指针。每个二维数组索引都包含三种类型的结构。

这是结构:

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 来创建我的 2D 数组指针:

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);

最佳答案

您的方式只是malloc'ed了数组的第一个维度。您需要malloc每一行:

struct cacheLine **cacheArray =  malloc(sizeof(struct cacheLine*)*S);
for(i = 0;i < S;i++) {
cacheLine[i] = malloc(sizeof(struct cacheLine) * E);
}

关于c - 使用 malloc 作为 2D 数组指针会导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19320695/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com