分配二维数组时出现分段错误?

时间:2018-10-07 20:24:20

标签: c segmentation-fault

我在第57行遇到了分段错误,不确定为什么...:

int[][] roomArray = 
{
    new [] {12, 10, 9},
    new [] {11, 8, 12},
    new [] {10, 10, 8},
    new [] {15, 12, 10}
};
roomArray.Select(x => new Room
    {
        Length = x[0],
        Width = x[1],
        Height = x[2],
    })
    .ToList()
    .ForEach(x =>
    {
        Write($"The room area is: {x.WallArea} gallons of paint needed is {x.GallonsOfPaint}");
    });

我缺少什么吗?我非常有信心自己分配正确。.

2 个答案:

答案 0 :(得分:1)

tagArray = (int **) malloc(numRows*sizeof(int)); // creates rows in array with C/K*L rows
lruArray = (int **) malloc(numRows*sizeof(int)); // creates rows in array with C/K*L rows

您必须为int*而不是int分配空间。

请勿在C中强制转换malloc()的结果!

答案 1 :(得分:1)

44    tagArray = malloc(numRows*sizeof(int *));
45    lruArray = malloc(numRows*sizeof(int *));
46  
47    for(int i = 0; i<numRows;i++)
48      {
49        tagArray[i] = malloc(numCols*sizeof(int));
50        lruArray[i] = malloc(numCols*sizeof(int));
51      }