我正在尝试为两个二维数组声明和分配内存。然而,当尝试为 itemFeatureQ[39][16816] 分配值时,我得到了一个分段库。我无法理解它,因为我有 2GB RAM,但堆上只使用了 19MB。这是代码;
double** reserveMemory(int rows, int columns)
{
double **array;
int i;
array = (double**) malloc(rows * sizeof(double *));
if(array == NULL)
{
fprintf(stderr, "out of memory\n");
return NULL;
}
for(i = 0; i < rows; i++)
{
array[i] = (double*) malloc(columns * sizeof(double *));
if(array == NULL)
{
fprintf(stderr, "out of memory\n");
return NULL;
}
}
return array;
}
void populateUserFeatureP(double **userFeatureP)
{
int x,y;
for(x = 0; x < CUSTOMERS; x++)
{
for(y = 0; y < FEATURES; y++)
{
userFeatureP[x][y] = 0;
}
}
}
void populateItemFeatureQ(double **itemFeatureQ)
{
int x,y;
for(x = 0; x < FEATURES; x++)
{
for(y = 0; y < MOVIES; y++)
{
printf("(%d,%d)\n", x, y);
itemFeatureQ[x][y] = 0;
}
}
}
int main(int argc, char *argv[]){
double **userFeatureP = reserveMemory(480189, 40);
double **itemFeatureQ = reserveMemory(40, 17770);
populateItemFeatureQ(itemFeatureQ);
populateUserFeatureP(userFeatureP);
return 0;
}
最佳答案
您有几个拼写错误 - 更改:
array[i] = (double*) malloc(columns * sizeof(double *));
if(array == NULL)
至:
array[i] = (double*) malloc(columns * sizeof(double));
if(array[i] == NULL)
关于c - 声明两个大型二维数组会导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3063085/