本文介绍了声明两个大的二维数组给分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图声明和两个二维数组分配内存。但是试图将值赋给itemFeatureQ时,[39] [16816]我得到一个分段保管库。因为我有2GB的RAM,只使用堆19MB我无法理解这一点。这里是code;
双** reserveMemory(INT行,诠释列)
{
双**阵列;
INT I;
阵列=(双**)的malloc(行*的sizeof(双*));
如果(阵列== NULL)
{
fprintf中(标准错误,内存不足的\\ n);
返回NULL;
}
对于(i = 0; I<行;我++)
{
数组[我] =(双*)malloc的(列* sizeof的(双*));
如果(阵列== NULL)
{
fprintf中(标准错误,内存不足的\\ n);
返回NULL;
}
} 返回数组;}无效populateUserFeatureP(双** userFeatureP)
{
INT X,Y; 为(X = 0; X<客户; X ++)
{
对于(Y = 0; Y<特点; Y ++)
{
userFeatureP [X] [Y] = 0;
}
}
}无效populateItemFeatureQ(双** itemFeatureQ)
{
INT X,Y; 为(X = 0; X&下;特征; X ++)
{
对于(Y = 0; Y<电影; Y ++)
{
的printf((%D,%D)\\ n,X,Y);
itemFeatureQ [X] [Y] = 0;
}
}
}INT主(INT ARGC,CHAR *的argv []){ 双** userFeatureP = reserveMemory(480189,40);
双** itemFeatureQ = reserveMemory(40,17770); populateItemFeatureQ(itemFeatureQ);
populateUserFeatureP(userFeatureP); 返回0;
}
解决方案
您有几个错字 - 变化:
数组[我] =(双*)malloc的(列* sizeof的(双*));
如果(阵列== NULL)
到
数组[我] =(双*)malloc的(列*的sizeof(双));
如果(阵列[我] == NULL)
i'm trying to declare and allocate memory for two 2d-arrays. However when trying to assign values to itemFeatureQ[39][16816] I get a segmentation vault. I can't understand it since I have 2GB of RAM and only using 19MB on the heap. Here is the code;
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;
}
解决方案
You have a couple of typos - change:
array[i] = (double*) malloc(columns * sizeof(double *));
if(array == NULL)
to:
array[i] = (double*) malloc(columns * sizeof(double));
if(array[i] == NULL)
这篇关于声明两个大的二维数组给分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!