c - 声明两个大型二维数组会导致段错误

标签 c arrays

我正在尝试为两个二维数组声明和分配内存。然而,当尝试为 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/

相关文章:

c++ - 无法使用指针打印二维矩阵的值

c - 在结构中填充数组字段

c# - 为什么我不能将对象(实际上是 object[])转换为 string[]?

c - 如何等待启动线程执行初始化代码

c - linux如何同步抢占计数

c# - 如何拆分包含方括号且其中有空格的字符串

c++ - 什么是空间开销(当引用 C++ 数组时)?

php - 如何在php中从数组列表生成数组

c - 带有小框 0 和 1 的 ubuntu 终端上的输出是什么?

c - 在 C (C89) 中使用 printf 打印 BUFSIZ 宏常量时使用什么说明符